路由器參考手冊
Router Reference
下面的部分重點介紹了一些路由器的核心概念。
The following sections highlight some core router concepts.
路由器匯入
Router imports
Angular 的 Router 是一個可選服務,它為指定的 URL 提供特定的元件檢視。它不是 Angular 核心的一部分,因此它位於自己的包 @angular/router
中。
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 and thus is in its own library package, @angular/router
.
從任何其它的 Angular 套件中匯入你需要的東西。
Import what you need from it as you would from any other Angular package.
import { RouterModule, Routes } from '@angular/router';
關於瀏覽器 URL 風格的更多資訊,請參閱 LocationStrategy
和瀏覽器 URL 風格。
For more on browser URL styles, see LocationStrategy
and browser URL styles.
配置
Configuration
帶路由的 Angular 應用中有一個 Router
服務的單例實例。當瀏覽器的 URL 發生變化時,該路由器會查詢相應的 Route
,以便根據它確定要顯示的元件。
A routed Angular application has one singleton instance of the Router
service. 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 } // <-- debugging purposes only
)
// other imports here
],
...
})
export class AppModule { }
appRoutes
路由陣列描述瞭如何導航。把它傳給模組的 imports
陣列中的 RouterModule.forRoot()
方法來配置路由器。
The appRoutes
array of routes describes how to navigate. Pass it to the RouterModule.forRoot()
method in the module imports
to configure the router.
每個 Route
都會把一個 URL path
對映到一個元件。路徑中沒有前導斜槓。路由器會為你解析並建構最終的 URL,這樣你就可以在應用檢視中導航時使用相對路徑和絕對路徑了。
Each Route
maps a URL path
to a component. There are no leading slashes in the path. The router parses and builds the final URL for you, which allows you to use both relative and absolute paths when navigating between application views.
第二個路由中的 :id
是路由引數的令牌。在像 /hero/42
這樣的 URL 中,“42”是 id
引數的值。相應的 HeroDetailComponent
用這個值來查詢並顯示 id
為 42 的英雄。
The :id
in the second route is a token for a route parameter. In a URL such as /hero/42
, "42" is the value of the id
parameter. The corresponding HeroDetailComponent
uses that value to find and present the hero whose id
is 42.
第三個路由中的 data
屬性是存放與該特定路由關聯的任意資料的地方。每個啟用的路由都可以訪問 data
屬性。可以用它來儲存頁面標題,麵包屑文字和其它唯讀靜態資料等專案。你可以嘗試使用解析器守衛來檢索動態資料。
The data
property in the third route is a place to store arbitrary data associated with this specific route. The data property is accessible within each activated route. Use it to store items such as page titles, breadcrumb text, and other read-only, static data. You can use the resolve guard to retrieve dynamic data.
第四個路由中的空路徑表示該應用的預設路徑 - 當 URL 中的路徑為空時通常要去的地方,就像它在剛進來時一樣。這個預設路由重新導向到了 /heroes
這個 URL 的路由,因此會顯示 HeroesListComponent
。
The empty path in the fourth route represents the default path for the application—the place to go when the path in the URL is empty, as it typically is at the start. This default route redirects to the route for the /heroes
URL and, therefore, displays the HeroesListComponent
.
如果你需要檢視導航生命週期中發生了什麼事件,可以把 enableTracing
選項作為路由器預設配置的一部分。這會把每個導航生命週期中發生的每個路由器事件都輸出到瀏覽器控制檯中。enableTracing
只會用於除錯目的。你可以把 enableTracing: true
選項作為第二個引數傳給 RouterModule.forRoot()
方法。
If you need to see what events are happening during the navigation lifecycle, there is the enableTracing
option as part of the router's default configuration. This outputs each router event that took place during each navigation lifecycle to the browser console. Use enableTracing
only for debugging purposes. You set the enableTracing: true
option in the object passed as the second argument to the RouterModule.forRoot()
method.
路由出口
Router outlet
RouterOutlet
是一個來自路由器函式庫的指令,雖然它的用法像元件一樣。它充當佔位符,用於在範本中標記出路由器應該顯示把該元件顯示在那個出口的位置。
The RouterOutlet
is a directive from the router library that is used like a component. It acts as a placeholder that marks the spot in the template where the router should display the components for that outlet.
<router-outlet></router-outlet>
<!-- Routed components go here -->
對於上面的配置,當這個應用的瀏覽器 URL 變為 /heroes
時,路由器就會把這個 URL 與路由路徑 /heroes
匹配,並把 HeroListComponent
作為兄弟元素顯示在宿主元件範本中的 RouterOutlet
下方。
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.
路由連結
Router links
要想透過某些使用者操作(比如單擊一下 a 標籤)進行導航,請使用 RouterLink
。
To navigate as a result of some user action such as the click of an anchor tag, use RouterLink
.
考慮下面的範本:
Consider the following template:
<h1>Angular Router</h1>
<nav>
<a routerLink="/crisis-center" routerLinkActive="active">Crisis Center</a>
<a routerLink="/heroes" routerLinkActive="active">Heroes</a>
</nav>
<router-outlet></router-outlet>
a 標籤上的 RouterLink
指令讓路由器可以控制這些元素。導航路徑是固定的,所以你可以給 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; that is, the link parameters array. The router resolves that array into a complete URL.
活動路由鏈路
Active router links
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 looks like routerLinkActive="..."
.
等號 =
右側的範本表示式,包含一個以空格分隔的 CSS 類別字串,當這個連結處於活動狀態時,路由器就會加上這些字串(並在非活動狀態時刪除)。你可以把 RouterLinkActive
指令設定成一串類別的字串,比如 [routerLinkActive]="'active fluffy'"
,也可以把它繫結到一個返回這樣一個字串的元件屬性上。
The template expression to the right of the equal sign, =
, contains a space-delimited string of CSS classes that the Router adds when this link is active (and removes 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.
活動路由連結會級聯到路由樹的每個級別,這樣父路由和子路由連結就可以同時處於活動狀態。要覆蓋這種行為,你可以用 { exact: true }
表示式繫結到 [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.
路由器狀態
Router state
每個成功的導航生命週期結束後,路由器都會建構一個 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.
啟用路由
Activated route
路由的路徑和引數可以透過注入名為 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 | 一個路由路徑的 An |
data | 包含提供給當前路由的 An |
paramMap | 一個包含該路由的必要引數和可選引數 map 的 An |
queryParamMap | 一個包含適用於所有路由的查詢引數 map 的 An |
fragment | 一個適用於所有路由的 URL 片段的 An |
outlet | 用來渲染該路由的 The name of the |
routeConfig | 包含原始路徑的那個路由的配置資訊。 The route configuration used for the route that contains the origin path. |
parent | 當該路由是子路由時,表示該路由的父級 The route's parent |
firstChild | 包含該路由的子路由列表中的第一個 Contains the first |
children | 包含當前路由下所有啟用的子路由。 Contains all the child routes activated under the current route. |
還有兩個較舊的屬性,但更推薦使用它們的替代品,因為它們可能會在以後的 Angular 版本中棄用。
Two older properties are still available; however, their replacements are preferable as they may be deprecated in a future Angular version.
params
:一個Observable
,它包含專屬於該路由的必要引數和可選引數。請改用paramMap
。params
: AnObservable
that contains the required and optional parameters specific to the route. UseparamMap
instead.queryParams
:一個包含可用於所有路由的查詢引數的Observable
。請改用queryParamMap
。queryParams
: AnObservable
that contains the query parameters available to all routes. UsequeryParamMap
instead.
路由器事件
Router events
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 | An event triggered before the |
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 | 當路由器開始進入路由守衛階段時觸發的事件。 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 | 當路由器成功結束了路由守衛階段時觸發的事件。 An event triggered when the Router finishes the Guards phase of routing successfully. |
ResolveStart | 當路由器開始路由解析階段時觸發的事件。 An event triggered when the Router begins the Resolve phase of routing. |
ResolveEnd | 當路由器的路由解析階段成功完成時觸發的事件。 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 |
NavigationError | 當導航由於非預期的錯誤而失敗時觸發的事件。 An event triggered when navigation fails due to an unexpected error. |
Scroll | 用來表示滾動的事件。 An event that represents a scrolling event. |
當啟用了 enableTracing
選項時,Angular 會把這些事件都記錄到控制檯。關於篩選路由器導航事件的範例,請參閱 Angular 中的 Observables 一章的路由器部分。
When you enable the enableTracing
option, Angular logs these events to the console. For an example of filtering router navigation events, see the router section of the Observables in Angular guide.
路由器術語
Router terminology
這裡是一些關鍵的 Router
術語及其含義:
Here are the key Router
terms and their meanings:
路由器部件 Router Part | 含義 Meaning |
---|---|
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 | 定義一個路由陣列,每一個條目都會把一個 URL 路徑對映到元件。 Defines an array of Routes, each mapping a URL path to a component. |
Route | 定義路由器如何基於一個 URL 模式導航到某個元件。 大部分路由都由一個路徑和一個元件類別組成。 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 | 該指令 ( The directive ( |
RouterLink | 用於將可點選的 HTML 元素繫結到某個路由的指令。單擊帶有 The directive for binding a clickable HTML element to a route. Clicking an element with a |
RouterLinkActive | 該指令會在元素上或元素內包含的相關 The directive for adding/removing classes from an HTML element when an associated |
ActivatedRoute | 一個提供給每個路由元件的服務,其中包含當前路由專屬的資訊,例如路由引數、靜態資料、解析資料、全域性查詢引數和全域性片段。 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 | 路由器的當前狀態,包括一棵當前啟用路由的樹以及遍歷這棵路由樹的便捷方法。 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 | 一個由路由器將其解釋為路由指南的陣列。你可以將該陣列繫結到 An array that the router interprets as a routing instruction. You can bind that array to a |
路由元件 Routing component | 一個帶有 An Angular component with a |