# In-app navigation: routing to views # 应用内导航:路由到视图 In a single-page app, you change what the user sees by showing or hiding portions of the display that correspond to particular components, rather than going out to the server to get a new page. As users perform application tasks, they need to move between the different [views](guide/glossary#view "Definition of view") that you have defined. To implement this kind of navigation within the single page of your app, you use the Angular **`Router`**. 在单页面应用中,你可以通过显示或隐藏特定组件的显示部分来改变用户能看到的内容,而不用去服务器获取新页面。当用户执行应用任务时,他们要在你预定义的不同[视图](guide/glossary#view "视图的定义")之间移动。要想在应用的单个页面中实现这种导航,你可以使用 Angular 的**`Router`**(路由器)。 To handle the navigation from one [view](guide/glossary#view) to the next, you use the Angular _router_. The router enables navigation by interpreting a browser URL as an instruction to change the view. 为了处理从一个[视图](guide/glossary#view)到下一个视图之间的导航,你可以使用 Angular 的*路由器*。路由器会把浏览器 URL 解释成改变视图的操作指南,以完成导航。 To explore a sample app featuring the router's primary features, see the . 要探索一个具备路由器主要功能的示例应用,请参见。 ## Prerequisites ## 先决条件 Before creating a route, you should be familiar with the following: 在创建路由之前,你应该熟悉以下内容: * [Basics of components](guide/architecture-components) [组件的基础知识](guide/architecture-components) * [Basics of templates](guide/glossary#template) [模板的基础知识](guide/glossary#template) * An Angular app—you can generate a basic Angular app using the [Angular CLI](cli). 一个 Angular 应用,你可以使用 [Angular CLI](cli) 生成一个基本的 Angular 应用。 For an introduction to Angular with a ready-made app, see [Getting Started](start). For a more in-depth experience of building an Angular app, see the [Tour of Heroes](tutorial) tutorial. Both guide you through using component classes and templates. 有关这个现成应用的 Angular 简介,请参见[快速上手](start)。有关构建 Angular 应用的更深入体验,请参见[英雄指南](tutorial)教程。两者都会指导你使用组件类和模板。
{@a basics} ## Generate an app with routing enabled ## 生成一个支持路由的应用 The following command uses the Angular CLI to generate a basic Angular app with an app routing module, called `AppRoutingModule`, which is an NgModule where you can configure your routes. The app name in the following example is `routing-app`. 下面的命令会用 Angular CLI 来生成一个带有应用路由模块(`AppRoutingModule`)的基本 Angular 应用,它是一个 NgModule,可用来配置路由。下面的例子中应用的名字是 `routing-app`。 ng new routing-app --routing When generating a new app, the CLI prompts you to select CSS or a CSS preprocessor. For this example, accept the default of `CSS`. 一旦生成新应用,CLI 就会提示你选择 CSS 或 CSS 预处理器。在这个例子中,我们接受 `CSS` 的默认值。 ### Adding components for routing ### 为路由添加组件 To use the Angular router, an app needs to have at least two components so that it can navigate from one to the other. To create a component using the CLI, enter the following at the command line where `first` is the name of your component: 为了使用 Angular 的路由器,应用至少要有两个组件才能从一个导航到另一个。要使用 CLI 创建组件,请在命令行输入以下内容,其中 `first` 是组件的名称: ng generate component first Repeat this step for a second component but give it a different name. Here, the new name is `second`. 为第二个组件重复这个步骤,但给它一个不同的名字。这里的新名字是 `second`。 ng generate component second The CLI automatically appends `Component`, so if you were to write `first-component`, your component would be `FirstComponentComponent`. CLI 会自动添加 `Component` 后缀,所以如果在编写 `first-component`,那么其组件名就是 `FirstComponentComponent`。 {@a basics-base-href}
#### `` This guide works with a CLI-generated Angular app. If you are working manually, make sure that you have `` in the `` of your index.html file. This assumes that the `app` folder is the application root, and uses `"/"`. 本指南适用于 CLI 生成的 Angular 应用。如果你是手动工作的,请确保你的 index.html 文件的 `` 中有 `` 语句。这里假定 `app` 文件夹是应用的根目录,并使用 `"/"` 作为基础路径。
### Importing your new components ### 导入这些新组件 To use your new components, import them into `AppRoutingModule` at the top of the file, as follows: 要使用这些新组件,请把它们导入到该文件顶部的 `AppRoutingModule` 中,具体如下: import { FirstComponent } from './first/first.component'; import { SecondComponent } from './second/second.component'; {@a basic-route} ## Defining a basic route ## 定义一个基本路由 There are three fundamental building blocks to creating a route. 创建路由有三个基本的构建块。 Import the `AppRoutingModule` into `AppModule` and add it to the `imports` array. 把 `AppRoutingModule` 导入 `AppModule` 并把它添加到 `imports` 数组中。 The Angular CLI performs this step for you. However, if you are creating an app manually or working with an existing, non-CLI app, verify that the imports and configuration are correct. The following is the default `AppModule` using the CLI with the `--routing` flag. Angular CLI 会为你执行这一步骤。但是,如果要手动创建应用或使用现存的非 CLI 应用,请验证导入和配置是否正确。下面是使用 `--routing` 标志生成的默认 `AppModule`。 1. Import `RouterModule` and `Routes` into your routing module. 把 `RouterModule` 和 `Routes` 导入到你的路由模块中。 The Angular CLI performs this step automatically. The CLI also sets up a `Routes` array for your routes and configures the `imports` and `exports` arrays for `@NgModule()`. Angular CLI 会自动执行这一步骤。CLI 还为你的路由设置了 `Routes` 数组,并为 `@NgModule()` 配置了 `imports` 和 `exports` 数组。 1. Define your routes in your `Routes` array. 在 `Routes` 数组中定义你的路由。 Each route in this array is a JavaScript object that contains two properties. The first property, `path`, defines the URL path for the route. The second property, `component`, defines the component Angular should use for the corresponding path. 这个数组中的每个路由都是一个包含两个属性的 JavaScript 对象。第一个属性 `path` 定义了该路由的 URL 路径。第二个属性 `component` 定义了要让 Angular 用作相应路径的组件。 1. Add your routes to your application. 把这些路由添加到你的应用中。 Now that you have defined your routes, you can add them to your application. First, add links to the two components. Assign the anchor tag that you want to add the route to the `routerLink` attribute. Set the value of the attribute to the component to show when a user clicks on each link. Next, update your component template to include ``. This element informs Angular to update the application view with the component for the selected route. 现在你已经定义了路由,可以把它们添加到应用中了。首先,添加到这两个组件的链接。把要添加路由的链接赋值给 `routerLink` 属性。将属性的值设置为该组件,以便在用户点击各个链接时显示这个值。接下来,修改组件模板以包含 `` 标签。该元素会通知 Angular,你可以用所选路由的组件更新应用的视图。 {@a route-order} ### Route order ### 路由顺序 The order of routes is important because the `Router` uses a first-match wins strategy when matching routes, so more specific routes should be placed above less specific routes. List routes with a static path first, followed by an empty path route, which matches the default route. The [wildcard route](guide/router#setting-up-wildcard-routes) comes last because it matches every URL and the `Router` selects it only if no other routes match first. 路由的顺序很重要,因为 `Router` 在匹配路由时使用“先到先得”策略,所以应该在不那么具体的路由前面放置更具体的路由。首先列出静态路径的路由,然后是一个与默认路由匹配的空路径路由。[通配符路由](guide/router#setting-up-wildcard-routes)是最后一个,因为它匹配每一个 URL,只有当其它路由都没有匹配时,`Router` 才会选择它。 {@a activated-route} ## Getting route information ## 获取路由信息 Often, as a user navigates your application, you want to pass information from one component to another. For example, consider an application that displays a shopping list of grocery items. Each item in the list has a unique `id`. To edit an item, users click an Edit button, which opens an `EditGroceryItem` component. You want that component to retrieve the `id` for the grocery item so it can display the right information to the user. 通常,当用户导航你的应用时,你会希望把信息从一个组件传递到另一个组件。例如,考虑一个显示杂货商品购物清单的应用。列表中的每一项都有一个唯一的 `id`。要想编辑某个项目,用户需要单击“编辑”按钮,打开一个 `EditGroceryItem` 组件。你希望该组件得到该商品的 `id`,以便它能向用户显示正确的信息。 You can use a route to pass this type of information to your application components. To do so, you use the [ActivatedRoute](api/router/ActivatedRoute) interface. 你也可以使用一个路由把这种类型的信息传给你的应用组件。要做到这一点,你可以使用 [ActivatedRoute](api/router/ActivatedRoute) 接口。 To get information from a route: 要从路由中获取信息: 1. Import `ActivatedRoute` and `ParamMap` to your component. 把 `ActivatedRoute` 和 `ParamMap` 导入你的组件。 These `import` statements add several important elements that your component needs. To learn more about each, see the following API pages: 这些 `import` 语句添加了组件所需的几个重要元素。要详细了解每个 API,请参阅以下 API 页面: * [`Router`](api/router) * [`ActivatedRoute`](api/router/ActivatedRoute) * [`ParamMap`](api/router/ParamMap) 1. Inject an instance of `ActivatedRoute` by adding it to your application's constructor: 通过把 `ActivatedRoute` 的一个实例添加到你的应用的构造函数中来注入它: 1. Update the `ngOnInit()` method to access the `ActivatedRoute` and track the `id` parameter: 更新 `ngOnInit()` 方法来访问这个 `ActivatedRoute` 并跟踪 `id` 参数: ngOnInit() { this.route.queryParams.subscribe(params => { this.name = params['name']; }); } Note: The preceding example uses a variable, `name`, and assigns it the value based on the `name` parameter. 注意:前面的例子使用了一个变量 `name`,并根据 `name` 参数给它赋值。 {@a wildcard-route-how-to} ## Setting up wildcard routes ## 设置通配符路由 A well-functioning application should gracefully handle when users attempt to navigate to a part of your application that does not exist. To add this functionality to your application, you set up a wildcard route. The Angular router selects this route any time the requested URL doesn't match any router paths. 当用户试图导航到那些不存在的应用部件时,在正常的应用中应该能得到很好的处理。要在应用中添加此功能,需要设置通配符路由。当所请求的 URL 与任何路由器路径都不匹配时,Angular 路由器就会选择这个路由。 To set up a wildcard route, add the following code to your `routes` definition. 要设置通配符路由,请在 `routes` 定义中添加以下代码。 { path: '**', component: } The two asterisks, `**`, indicate to Angular that this `routes` definition is a wildcard route. For the component property, you can define any component in your application. Common choices include an application-specific `PageNotFoundComponent`, which you can define to [display a 404 page](guide/router#404-page-how-to) to your users; or a redirect to your application's main component. A wildcard route is the last route because it matches any URL. For more detail on why order matters for routes, see [Route order](guide/router#route-order). 这两个星号 `**` 告诉 Angular,这个 `routes` 定义是通配符路由。对于 component 属性,你可以使用应用中的任何组件。常见的选择包括应用专属的 `PageNotFoundComponent`,你可以定义它来向用户[展示 404 页面](guide/router#404-page-how-to),或者跳转到应用的主组件。通配符路由是最后一个路由,因为它匹配所有的 URL。有关路由顺序的更多详细信息,请参阅[路由顺序](guide/router#route-order)。 {@a 404-page-how-to} ## Displaying a 404 page ## 显示 404 页面 To display a 404 page, set up a [wildcard route](guide/router#wildcard-route-how-to) with the `component` property set to the component you'd like to use for your 404 page as follows: 要显示 404 页面,请设置一个[通配符路由](guide/router#wildcard-route-how-to),并将 `component` 属性设置为你要用于 404 页面的组件,如下所示: The last route with the `path` of `**` is a wildcard route. The router selects this route if the requested URL doesn't match any of the paths earlier in the list and sends the user to the `PageNotFoundComponent`. `path` 为 `**` 的最后一条路由是通配符路由。如果请求的 URL 与前面列出的路径不匹配,路由器会选择这个路由,并把该用户送到 `PageNotFoundComponent`。 ## Setting up redirects ## 设置重定向 To set up a redirect, configure a route with the `path` you want to redirect from, the `component` you want to redirect to, and a `pathMatch` value that tells the router how to match the URL. 要设置重定向,请使用重定向源的 `path`、要重定向目标的 `component` 和一个 `pathMatch` 值来配置路由,以告诉路由器该如何匹配 URL。 In this example, the third route is a redirect so that the router defaults to the `first-component` route. Notice that this redirect precedes the wildcard route. Here, `path: ''` means to use the initial relative URL (`''`). 在这个例子中,第三个路由是重定向路由,所以路由器会默认跳到 `first-component` 路由。注意,这个重定向路由位于通配符路由之前。这里的 `path: ''` 表示使用初始的相对 URL( `''` )。 For more details on `pathMatch` see [Spotlight on `pathMatch`](guide/router#pathmatch). 有关 `pathMatch` 的详情,请参阅[聚焦 `pathMatch`](guide/router#pathmatch)部分。 {@a nesting-routes} ## Nesting routes ## 嵌套路由 As your application grows more complex, you may want to create routes that are relative to a component other than your root component. These types of nested routes are called child routes. This means you're adding a second `` to your app, because it is in addition to the `` in `AppComponent`. 随着你的应用变得越来越复杂,你可能要创建一些根组件之外的相对路由。这些嵌套路由类型称为子路由。这意味着你要为你的应用添加第二 ``,因为它是 `AppComponent` 之外的另一个 ``。 In this example, there are two additional child components, `child-a`, and `child-b`. Here, `FirstComponent` has its own `