Angular

您所在的位置:网站首页 angular菜单导航 Angular

Angular

2024-02-02 00:07| 来源: 网络整理| 查看: 265

路由与导航link概览基础知识 元素从路由库中导入配置路由出口路由器链接路由链接的激活状态路由器状态激活的路由路由事件总结一下范例应用范例程序的动图里程碑 1:起步定义路由注册路由器与路由定义添加路由出口定义通配符路由设置跳转“起步阶段”总结里程碑 2:路由模块把路由集成到应用中将路由配置重构为路由模块你需要路由模块吗?里程碑 3: 英雄特征区添加英雄管理功能导入模块的顺序很重要路由参数Activated Route 实战导航回列表组件ActivatedRoute 服务中的路由参数添加路由动画里程碑 3 的总结里程碑 4:危机中心带有子路由的危机中心子路由组件子路由配置把危机中心模块导入到 AppModule 的路由中相对导航使用相对 URL 导航到危机列表用命名出口(outlet)显示多重路由里程碑 5:路由守卫CanActivate: 要求认证CanActivateChild:保护子路由CanDeactivate:处理未保存的更改Resolve: 预先获取组件数据查询参数及片段里程碑 6:异步路由惰性加载路由配置CanLoad 守卫:保护对特性模块的未授权加载预加载:特性区的后台加载自定义预加载策略使用重定向迁移 URL把 /heroes 修改为 /superheros审查路由器配置总结与最终的应用附录附录:链接参数数组附录:LocationStrategy 以及浏览器 URL 样式Routing and navigationlink

在用户使用应用程序时,Angular 的路由器能让用户从一个视图导航到另一个视图。

The Angular Routerenables navigation from one view to the next as users perform application tasks.

本章涵盖了该路由器的主要特性,通过一个小型应用的成长演进来讲解它。参见现场演练 / 下载范例。

This guide covers the router's primary features, illustrating them through the evolution of a small application that you canrun live in the browserrun live in the browser / 下载范例.

概览linkOverviewlink

浏览器具有熟悉的导航模式:

The browser is a familiar model of application navigation:

在地址栏输入 URL,浏览器就会导航到相应的页面。

Enter a URL in the address bar and the browser navigates to a corresponding page.

在页面中点击链接,浏览器就会导航到一个新页面。

Click links on the page and the browser navigates to a new page.

点击浏览器的前进和后退按钮,浏览器就会在你的浏览历史中向前或向后导航。

Click the browser's back and forward buttons and the browser navigates backward and forward through the history of pages you've seen.

Angular 的 Router(即“路由器”)借鉴了这个模型。它把浏览器中的 URL 看做一个操作指南, 据此导航到一个由客户端生成的视图,并可以把参数传给支撑视图的相应组件,帮它决定具体该展现哪些内容。 你可以为页面中的链接绑定一个路由,这样,当用户点击链接时,就会导航到应用中相应的视图。 当用户点击按钮、从下拉框中选取,或响应来自任何地方的事件时,你也可以在代码控制下进行导航。 路由器还在浏览器的历史日志中记录下这些活动,这样浏览器的前进和后退按钮也能照常工作。

The Angular Router ("the router") borrows from this model. It can interpret a browser URL as an instruction to navigate to a client-generated view. It can pass optional parameters along to the supporting view component that help it decide what specific content to present. You can bind the router to links on a page and it will navigate to the appropriate application view when the user clicks a link. You can navigate imperatively when the user clicks a button, selects from a drop box, or in response to some other stimulus from any source. And the router logs activity in the browser's history journal so the back and forward buttons work as well.

基础知识linkThe Basicslink

本章包括一系列里程碑,从一个单模块、两个页面的简单程序逐步走向带有多个子路由的多视图设计。

This guide proceeds in phases, marked by milestones, starting from a simple two-pager and building toward a modular, multi-view design with child routes.

先对路由的一些核心概念做一个介绍,它能帮你逐步过渡到细节。

An introduction to a few core router concepts will help orient you to the details that follow.

元素linklink

大多数带路由的应用都要在index.html的 标签下先添加一个 元素,来告诉路由器该如何合成导航用的 URL。

Most routing applications should add a element to the index.html as the first child in the tag to tell the router how to compose navigation URLs.

如果 app 文件夹是该应用的根目录(就像范例应用中一样),那就把 href 的值设置为下面这样:

If the app folder is the application root, as it is for the sample application, set the href value exactly as shown here.

src/index.html (base-href) 从路由库中导入linkRouter importslink

Angular 的路由器是一个可选的服务,它用来呈现指定的 URL 所对应的视图。 它并不是 Angular 核心库的一部分,而是在它自己的 @angular/router 包中。 像其它 Angular 包一样,你可以从它导入所需的一切。

The Angular Router is an optional service that presents a particular component view for a given URL. It is not part of the Angular core. It is in its own library package, @angular/router. Import what you need from it as you would from any other Angular package.

import { RouterModule, Routes } from '@angular/router';src/app/app.module.ts (import) import { RouterModule, Routes } from '@angular/router';

你将会在后面学到更多选项。

You'll learn about more options in the details below.

配置linkConfigurationlink

每个带路由的 Angular 应用都有一个Router(路由器)服务的单例对象。 当浏览器的 URL 变化时,路由器会查找对应的 Route(路由),并据此决定该显示哪个组件。

A routed Angular application has one singleton instance of the Routerservice. When the browser's URL changes, that router looks for a corresponding Route from which it can determine the component to display.

路由器需要先配置才会有路由信息。 下面的例子创建了五个路由定义,并用 RouterModule.forRoot() 方法来配置路由器, 并把它的返回值添加到 AppModule 的 imports 数组中。

A router has no routes until you configure it. The following example creates five route definitions, configures the router via the RouterModule.forRoot() method, and adds the result to the AppModule's imports array.

const appRoutes: Routes = [ { path: 'crisis-center', component: CrisisListComponent }, { path: 'hero/:id', component: HeroDetailComponent }, { path: 'heroes', component: HeroListComponent, data: { title: 'Heroes List' } }, { path: '', redirectTo: '/heroes', pathMatch: 'full' }, { path: '**', component: PageNotFoundComponent } ]; @NgModule({ imports: [ RouterModule.forRoot( appRoutes, { enableTracing: true } //

有了这份配置,当本应用在浏览器中的 URL 变为 /heroes 时,路由器就会匹配到 path 为 heroes 的 Route,并在宿主视图中的RouterOutlet之后显示 HeroListComponent 组件。

Given the configuration above, when the browser URL for this application becomes /heroes, the router matches that URL to the route path /heroes and displays the HeroListComponent as a sibling element to the RouterOutlet that you've placed in the host component's template.

路由器链接linkRouter linkslink

现在,你已经有了配置好的一些路由,还找到了渲染它们的地方,但又该如何导航到它呢?固然,从浏览器的地址栏直接输入 URL 也能做到,但是大多数情况下,导航是某些用户操作的结果,比如点击一个 A 标签。

Now you have routes configured and a place to render them, but how do you navigate? The URL could arrive directly from the browser address bar. But most of the time you navigate as a result of some user action such as the click of an anchor tag.

考虑下列模板:

Consider the following template:

Angular Router Crisis Center Heroes src/app/app.component.html Angular Router Crisis Center Heroes

a 标签上的 RouterLink 指令让路由器得以控制这个 a 元素。 这里的导航路径是固定的,因此可以把一个字符串赋给 routerLink(“一次性”绑定)。

The RouterLink directives on the anchor tags give the router control over those elements. The navigation paths are fixed, so you can assign a string to the routerLink (a "one-time" binding).

如果需要更加动态的导航路径,那就把它绑定到一个返回链接参数数组的模板表达式。 路由器会把这个数组解析成完整的 URL。

Had the navigation path been more dynamic, you could have bound to a template expression that returned an array of route link parameters (the link parameters array). The router resolves that array into a complete URL.

路由链接的激活状态linkActive router linkslink

RouterLinkActive 指令会基于当前的 RouterState 为活动的 RouterLink 切换所绑定的 css 类。

The RouterLinkActive directive toggles css classes for active RouterLink bindings based on the current RouterState.

在每个 A 标签上,你会看到一个到 RouterLinkActive 的属性绑定,形如 routerLinkActive="..."。

On each anchor tag, you see a property binding to the RouterLinkActive directive that look like routerLinkActive="...".

等号右边的模板表达式包含一些用空格分隔的 CSS 类名,当这个链接激活时,路由器将会把它们加上去(并在处于非活动状态时移除)。你还可以把 RouterLinkActive 设置为一个类组成的字符串,如 [routerLinkActive]="'active fluffy'",或把它绑定到一个返回类似字符串的组件属性。

The template expression to the right of the equals (=) contains a space-delimited string of CSS classes that the Router will add when this link is active (and remove when the link is inactive). You set the RouterLinkActive directive to a string of classes such as [routerLinkActive]="'active fluffy'" or bind it to a component property that returns such a string.

路由链接的激活状态会向下级联到路由树中的每个层级,所以,父子路由链接可能会同时激活。要覆盖这种行为,可以把 [routerLinkActiveOptions] 绑定为 { exact: true } 表达式,这样 RouterLink 只有当 URL 与当前 URL 精确匹配时才会激活。

Active route links cascade down through each level of the route tree, so parent and child router links can be active at the same time. To override this behavior, you can bind to the [routerLinkActiveOptions] input binding with the { exact: true } expression. By using { exact: true }, a given RouterLink will only be active if its URL is an exact match to the current URL.

路由器状态linkRouter statelink

在导航时的每个生命周期成功完成时,路由器会构建出一个 ActivatedRoute 组成的树,它表示路由器的当前状态。 你可以在应用中的任何地方用 Router 服务及其 routerState 属性来访问当前的 RouterState 值。

After the end of each successful navigation lifecycle, the router builds a tree of ActivatedRoute objects that make up the current state of the router. You can access the current RouterState from anywhere in the application using the Router service and the routerState property.

RouterState 中的每个 ActivatedRoute 都提供了从任意激活路由开始向上或向下遍历路由树的一种方式,以获得关于父、子、兄弟路由的信息。

Each ActivatedRoute in the RouterState provides methods to traverse up and down the route tree to get information from parent, child and sibling routes.

激活的路由linkActivated routelink

该路由的路径和参数可以通过注入进来的一个名叫ActivatedRoute的路由服务来获取。 它有一大堆有用的信息,包括:

The route path and parameters are available through an injected router service called the ActivatedRoute. It has a great deal of useful information including:

属性

Property

说明

Description

url

路由路径的 Observable 对象,是一个由路由路径中的各个部分组成的字符串数组。

An Observable of the route path(s), represented as an array of strings for each part of the route path.

data

一个 Observable,其中包含提供给路由的 data 对象。也包含由解析守卫(resolve guard)解析而来的值。

An Observable that contains the data object provided for the route. Also contains any resolved values from the resolve guard.

paramMap

一个 Observable,其中包含一个由当前路由的必要参数和可选参数组成的map对象。用这个 map 可以获取来自同名参数的单一值或多重值。

An Observable that contains a map of the required and optional parameters specific to the route. The map supports retrieving single and multiple values from the same parameter.

queryParamMap

一个 Observable,其中包含一个对所有路由都有效的查询参数组成的map对象。 用这个 map 可以获取来自查询参数的单一值或多重值。

An Observable that contains a map of the query parameters available to all routes. The map supports retrieving single and multiple values from the query parameter.

fragment

一个适用于所有路由的 URL 的 fragment(片段)的 Observable。

An Observable of the URL fragment available to all routes.

outlet

要把该路由渲染到的 RouterOutlet 的名字。对于无名路由,它的路由名是 primary,而不是空串。

The name of the RouterOutlet used to render the route. For an unnamed outlet, the outlet name is primary.

routeConfig

用于该路由的路由配置信息,其中包含原始路径。

The route configuration used for the route that contains the origin path.

parent

当该路由是一个子路由时,表示该路由的父级 ActivatedRoute。

The route's parent ActivatedRoute when this route is a child route.

firstChild

包含该路由的子路由列表中的第一个 ActivatedRoute。

Contains the first ActivatedRoute in the list of this route's child routes.

children

包含当前路由下所有已激活的子路由。

Contains all the child routes activated under the current route.

有两个旧式属性仍然是有效的,但它们不如其替代品那样强力,建议不再用它们,它们还将在未来的 Angular 版本中废弃。

Two older properties are still available. They are less capable than their replacements, discouraged, and may be deprecated in a future Angular version.

params—— 一个 Observable 对象,其中包含当前路由的必要参数和可选参数。请改用 paramMap。

params—An Observable that contains the required and optional parameters specific to the route. Use paramMap instead.

queryParams—— 一个 Observable 对象,其中包含对所有路由都有效的查询参数。请改用 queryParamMap。

queryParams—An Observable that contains the query parameters available to all routes. Use queryParamMap instead.

路由事件linkRouter eventslink

在每次导航中,Router 都会通过 Router.events 属性发布一些导航事件。这些事件的范围涵盖了从开始导航到结束导航之间的很多时间点。下表中列出了全部导航事件:

During each navigation, the Router emits navigation events through the Router.events property. These events range from when the navigation starts and ends to many points in between. The full list of navigation events is displayed in the table below.

路由器事件

Router Event

说明

Description

NavigationStart

本事件会在导航开始时触发。

An event triggered when navigation starts.

RouteConfigLoadStart

本事件会在 Router 惰性加载 某个路由配置之前触发。

An event triggered before the Router lazy loads a route configuration.

RouteConfigLoadEnd

本事件会在惰性加载了某个路由后触发。

An event triggered after a route has been lazy loaded.

RoutesRecognized

本事件会在路由器解析完 URL,并识别出了相应的路由时触发

An event triggered when the Router parses the URL and the routes are recognized.

GuardsCheckStart

本事件会在路由器开始 Guard 阶段之前触发。

An event triggered when the Router begins the Guards phase of routing.

ChildActivationStart

本事件会在路由器开始激活路由的子路由时触发。

An event triggered when the Router begins activating a route's children.

ActivationStart

本事件会在路由器开始激活某个路由时触发。

An event triggered when the Router begins activating a route.

GuardsCheckEnd

本事件会在路由器成功完成了 Guard 阶段时触发。

An event triggered when the Router finishes the Guards phase of routing successfully.

ResolveStart

本事件会在 Router 开始解析(Resolve)阶段时触发。

An event triggered when the Router begins the Resolve phase of routing.

ResolveEnd

本事件会在路由器成功完成了路由的解析(Resolve)阶段时触发。

An event triggered when the Router finishes the Resolve phase of routing successfuly.

ChildActivationEnd

本事件会在路由器激活了路由的子路由时触发。

An event triggered when the Router finishes activating a route's children.

ActivationEnd

本事件会在路由器激活了某个路由时触发。

An event triggered when the Router finishes activating a route.

NavigationEnd

本事件会在导航成功结束之后触发。

An event triggered when navigation ends successfully.

NavigationCancel

本事件会在导航被取消之后触发。 这可能是因为在导航期间某个路由守卫返回了 false。

An event triggered when navigation is canceled. This can happen when a Route Guard returns false during navigation, or redirects by returning a UrlTree.

NavigationError

这个事件会在导航由于意料之外的错误而失败时触发。

An event triggered when navigation fails due to an unexpected error.

Scroll

本事件代表一个滚动事件。

An event that represents a scrolling event.

当启用了 enableTracing 选项时,这些事件也同时会记录到控制台中。要想查看对路由导航事件进行过滤的例子,请访问 Angular 中的可观察对象一章的路由器部分

These events are logged to the console when the enableTracing option is enabled also. For an example of filtering router navigation events, visit the router section of the Observables in Angular guide.

总结一下linkSummarylink

该应用有一个配置过的路由器。 外壳组件中有一个 RouterOutlet,它能显示路由器所生成的视图。 它还有一些 RouterLink,用户可以点击它们,来通过路由器进行导航。

The application has a configured router. The shell component has a RouterOutlet where it can display views produced by the router. It has RouterLinks that users can click to navigate via the router.

下面是一些路由器中的关键词汇及其含义:

Here are the key Router terms and their meanings:

路由器部件

Router Part

含义

Meaning

Router(路由器)

Router

为激活的 URL 显示应用组件。管理从一个组件到另一个组件的导航

Displays the application component for the active URL. Manages navigation from one component to the next.

RouterModule

一个独立的 NgModule,用于提供所需的服务提供者,以及用来在应用视图之间进行导航的指令。

A separate NgModule that provides the necessary service providers and directives for navigating through application views.

Routes(路由数组)

Routes

定义了一个路由数组,每一个都会把一个 URL 路径映射到一个组件。

Defines an array of Routes, each mapping a URL path to a component.

Route(路由)

Route

定义路由器该如何根据 URL 模式(pattern)来导航到组件。大多数路由都由路径和组件类构成。

Defines how the router should navigate to a component based on a URL pattern. Most routes consist of a path and a component type.

RouterOutlet(路由出口)

RouterOutlet

该指令()用来标记出路由器该在哪里显示视图。

The directive () that marks where the router displays a view.

RouterLink(路由链接)

RouterLink

这个指令把可点击的 HTML 元素绑定到某个路由。点击带有 routerLink 指令(绑定到字符串或链接参数数组)的元素时就会触发一次导航。

The directive for binding a clickable HTML element to a route. Clicking an element with a routerLink directive that is bound to a string or a link parameters array triggers a navigation.

RouterLinkActive(活动路由链接)

RouterLinkActive

当 HTML 元素上或元素内的routerLink变为激活或非激活状态时,该指令为这个 HTML 元素添加或移除 CSS 类。

The directive for adding/removing classes from an HTML element when an associated routerLink contained on or inside the element becomes active/inactive.

ActivatedRoute(激活的路由)

ActivatedRoute

为每个路由组件提供的一个服务,它包含特定于路由的信息,比如路由参数、静态数据、解析数据、全局查询参数和全局碎片(fragment)。

A service that is provided to each route component that contains route specific information such as route parameters, static data, resolve data, global query params, and the global fragment.

RouterState(路由器状态)

RouterState

路由器的当前状态包含了一棵由程序中激活的路由构成的树。它包含一些用于遍历路由树的快捷方法。

The current state of the router including a tree of the currently activated routes together with convenience methods for traversing the route tree.

链接参数数组

Link parameters array

这个数组会被路由器解释成一个路由操作指南。你可以把一个RouterLink绑定到该数组,或者把它作为参数传给Router.navigate方法。

An array that the router interprets as a routing instruction. You can bind that array to a RouterLink or pass the array as an argument to the Router.navigate method.

路由组件

Routing component

一个带有RouterOutlet的 Angular 组件,它根据路由器的导航来显示相应的视图。

An Angular component with a RouterOutlet that displays views based on router navigations.

范例应用linkThe sample applicationlink

本章要讲的是如何开发一个带路由的多页面应用。 接下来会重点讲它的设计决策,并描述路由的关键特性,比如:

This guide describes development of a multi-page routed sample application. Along the way, it highlights design decisions and describes key features of the router such as:

把应用的各个特性组织成模块。

Organizing the application features into modules.

导航到组件(Heroes 链接到“英雄列表”组件)。

Navigating to a component (Heroes link to "Heroes List").

包含一个路由参数(当路由到“英雄详情”时,把该英雄的 id 传进去)。

Including a route parameter (passing the Hero id while routing to the "Hero Detail").

子路由(危机中心特性有一组自己的路由)。

Child routes (the Crisis Center has its own routes).

CanActivate 守卫(检查路由的访问权限)。

The CanActivate guard (checking route access).

CanActivateChild 守卫(检查子路由的访问权限)。

The CanActivateChild guard (checking child route access).

CanDeactivate 守卫(询问是否丢弃未保存的更改)。

The CanDeactivate guard (ask permission to discard unsaved changes).

Resolve 守卫(预先获取路由数据)。

The Resolve guard (pre-fetching route data).

惰性加载特性模块。

Lazy loading feature modules.

CanLoad 守卫(在加载特性模块之前进行检查)。

The CanLoad guard (check before loading feature module assets).

如果打算一步步构建出本应用,本章就会经过一系列里程碑。 但是,本章并不是一个教程,它隐藏了构造 Angular 应用的细节,那些细节会在本文档的其它地方展开。

The guide proceeds as a sequence of milestones as if you were building the app step-by-step. But, it is not a tutorial and it glosses over details of Angular application construction that are more thoroughly covered elsewhere in the documentation.

本应用的最终版源码可以在现场演练 / 下载范例中查看和下载。

The full source for the final version of the app can be seen and downloaded from the现场演练 / 下载范例.

范例程序的动图linkThe sample application in actionlink

假设本程序会用来帮助“英雄管理局”运行他们的业务。 英雄们需要找工作,而“英雄管理局”为他们寻找待解决的危机。

Imagine an application that helps the Hero Employment Agency run its business. Heroes need work and the agency finds crises for them to solve.

本应用具有三个主要的特性区:

The application has three main feature areas:

危机中心用于维护要指派给英雄的危机列表。

A Crisis Center for maintaining the list of crises for assignment to heroes.

英雄区用于维护管理局雇佣的英雄列表。

A Heroes area for maintaining the list of heroes employed by the agency.

管理区会管理危机和英雄的列表。

An Admin area to manage the list of crises and heroes.

点击英雄职介中心的现场演练 / 下载范例试用一下。

Try it by clicking on thislive example linklive example link / 下载范例.

等应用热身完毕,你就会看到一排导航按钮,以及一个英雄列表视图。

Once the app warms up, you'll see a row of navigation buttons and the Heroes view with its list of heroes.

选择其中之一,该应用就会把你带到此英雄的编辑页面。

Select one hero and the app takes you to a hero editing screen.

修改完名字,再点击“后退”按钮,应用又回到了英雄列表页,其中显示的英雄名已经变了。注意,对名字的修改会立即生效。

Alter the name. Click the "Back" button and the app returns to the heroes list which displays the changed hero name. Notice that the name change took effect immediately.

另外你也可以点击浏览器本身的后退按钮,这样也同样会回到英雄列表页。 在 Angular 应用中导航也会和标准的 Web 导航一样更新浏览器中的历史。

Had you clicked the browser's back button instead of the "Back" button, the app would have returned you to the heroes list as well. Angular app navigation updates the browser history as normal web navigation does.

现在,点击危机中心链接,前往危机列表页。

Now click the Crisis Center link for a list of ongoing crises.

选择其中之一,该应用就会把你带到此危机的编辑页面。 危机详情是当前页的子组件,就在列表的紧下方。

Select a crisis and the application takes you to a crisis editing screen. The Crisis Detail appears in a child component on the same page, beneath the list.

修改危机的名称。 注意,危机列表中的相应名称并没有修改。

Alter the name of a crisis. Notice that the corresponding name in the crisis list does not change.

这和英雄详情页略有不同。英雄详情会立即保存你所做的更改。 而危机详情页中,你的更改都是临时的 —— 除非按“保存”按钮保存它们,或者按“取消”按钮放弃它们。 这两个按钮都会导航回危机中心,显示危机列表。

Unlike Hero Detail, which updates as you type, Crisis Detail changes are temporary until you either save or discard them by pressing the "Save" or "Cancel" buttons. Both buttons navigate back to the Crisis Center and its list of crises.

先不要点击这些按钮。 而是点击浏览器的后退按钮,或者点击“Heroes”链接。

Do not click either button yet. Click the browser back button or the "Heroes" link instead.

这时会弹出一个对话框。

Up pops a dialog box.

你可以回答“确定”以放弃这些更改,或者回答“取消”来继续编辑。

You can say "OK" and lose your changes or click "Cancel" and continue editing.

这种行为的幕后是路由器的 CanDeactivate 守卫。 该守卫让你有机会进行清理工作或在离开当前视图之前请求用户的许可。

Behind this behavior is the router's CanDeactivate guard. The guard gives you a chance to clean-up or ask the user's permission before navigating away from the current view.

Admin 和 Login 按钮用于演示路由器的其它能力,本章稍后的部分会讲解它们。这里只是个简短的讲解。

The Admin and Login buttons illustrate other router capabilities to be covered later in the guide. This short introduction will do for now.

这就开始本应用的第一个里程碑。

Proceed to the first application milestone.

里程碑 1:起步linkMilestone 1: Getting startedlink

开始本应用的一个简版,它在两个空路由之间导航。

Begin with a simple version of the app that navigates between two empty views.

遵循这些步骤生成一个范例应用。

Generate a sample application to follow the walkthrough.

ng new angular-router-sample ng new angular-router-sample 定义路由linkDefine Routeslink

路由器必须用“路由定义”的列表进行配置。

A router must be configured with a list of route definitions.

每个定义都被翻译成了一个Route对象。该对象有一个 path 字段,表示该路由中的 URL 路径部分,和一个 component 字段,表示与该路由相关联的组件。

Each definition translates to a Route object which has two things: a path, the URL path segment for this route; and a component, the component associated with this route.

当浏览器的 URL 变化时或在代码中告诉路由器导航到一个路径时,路由器就会翻出它用来保存这些路由定义的注册表。

The router draws upon its registry of definitions when the browser URL changes or when application code tells the router to navigate along a route path.

直白的说,你可以这样解释第一个路由:

In simpler terms, you might say this of the first route:

当浏览器地址栏的 URL 变化时,如果它匹配上了路径部分 /crisis-center,路由器就会激活一个 CrisisListComponent 的实例,并显示它的视图。

When the browser's location URL changes to match the path segment /crisis-center, then the router activates an instance of the CrisisListComponent and displays its view.

当应用程序请求导航到路径 /crisis-center 时,路由器激活一个 CrisisListComponent 的实例,显示它的视图,并将该路径更新到浏览器地址栏和历史。

When the application requests navigation to the path /crisis-center, the router activates an instance of CrisisListComponent, displays its view, and updates the browser's address location and history with the URL for that path.

第一个配置定义了由两个路由构成的数组,它们用简单的路径指向了 CrisisListComponent 和 HeroListComponent。来生成 CrisisList 和 HeroList。

The first configuration defines an array of two routes with simple paths leading to the CrisisListComponent and HeroListComponent. Generate the CrisisList and HeroList components.

ng generate component crisis-list ng generate component crisis-list ng generate component hero-list ng generate component hero-list

把每个组件的内容都替换成下列范例 HTML。

Replace the contents of each component with the sample HTML below.

CRISIS CENTER

Get your crisis here

HEROES

Get your heroes here

src/app/crisis-list/crisis-list.component.htmlsrc/app/hero-list/hero-list.component.html CRISIS CENTER

Get your crisis here

注册路由器与路由定义linkRegister Router and Routeslink

要使用路由器,必须先注册来自 @angular/router 包中的 RouterModule。 定义一个路由数组 appRoutes 并把它传给 RouterModule.forRoot() 方法。 它会返回一个模块,其中包含配置好的 Router 服务提供者,以及路由库所需的其它提供者。 一旦启动了应用,Router 就会根据当前的浏览器 URL 进行首次导航。

In order to use the Router, you must first register the RouterModule from the @angular/router package. Define an array of routes, appRoutes, and pass them to the RouterModule.forRoot() method. It returns a module, containing the configured Router service provider, plus other providers that the routing library requires. Once the application is bootstrapped, the Router performs the initial navigation based on the current browser URL.

注意: RouterModule.forRoot 方法是用于注册全应用级提供者的编码模式。要详细了解全应用级提供者,参见单例服务 一章。

Note: The RouterModule.forRoot method is a pattern used to register application-wide providers. Read more about application-wide providers in the Singleton services guide.

import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { RouterModule, Routes } from '@angular/router'; import { AppComponent } from './app.component'; import { CrisisListComponent } from './crisis-list/crisis-list.component'; import { HeroListComponent } from './hero-list/hero-list.component'; const appRoutes: Routes = [ { path: 'crisis-center', component: CrisisListComponent }, { path: 'heroes', component: HeroListComponent }, ]; @NgModule({ imports: [ BrowserModule, FormsModule, RouterModule.forRoot( appRoutes, { enableTracing: true } //


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3