填寫這份《一分鐘調查》,幫我們(開發組)做得更好!去填寫Home

Router

一個提供導航和操縱 URL 能力的 NgModule。

A service that provides navigation among views and URL manipulation capabilities.

      
      class Router {
  constructor(rootComponentType: Type<any>, urlSerializer: UrlSerializer, rootContexts: ChildrenOutletContexts, location: Location, injector: Injector, loader: NgModuleFactoryLoader, compiler: Compiler, config: Route[])
  events: Observable<Event>
  routerState: RouterState
  errorHandler: ErrorHandler
  malformedUriErrorHandler: (error: URIError, urlSerializer: UrlSerializer, url: string) => UrlTree
  navigated: boolean
  urlHandlingStrategy: UrlHandlingStrategy
  routeReuseStrategy: RouteReuseStrategy
  onSameUrlNavigation: 'reload' | 'ignore'
  paramsInheritanceStrategy: 'emptyOnly' | 'always'
  urlUpdateStrategy: 'deferred' | 'eager'
  relativeLinkResolution: 'legacy' | 'corrected'
  config: Routes
  url: string
  initialNavigation(): void
  setUpLocationChangeListener(): void
  getCurrentNavigation(): Navigation | null
  resetConfig(config: Route[]): void
  dispose(): void
  createUrlTree(commands: any[], navigationExtras: UrlCreationOptions = {}): UrlTree
  navigateByUrl(url: string | UrlTree, extras: NavigationBehaviorOptions = {...}): Promise<boolean>
  navigate(commands: any[], extras: NavigationExtras = { skipLocationChange: false }): Promise<boolean>
  serializeUrl(url: UrlTree): string
  parseUrl(url: string): UrlTree
  isActive(url: string | UrlTree, matchOptions: boolean | IsActiveMatchOptions): boolean
}
    

參見

Provided in

建構函式

建立路由器服務。

Creates the router service.

      
      constructor(rootComponentType: Type<any>, urlSerializer: UrlSerializer, rootContexts: ChildrenOutletContexts, location: Location, injector: Injector, loader: NgModuleFactoryLoader, compiler: Compiler, config: Route[])
    
引數
rootComponentType Type
urlSerializer UrlSerializer
rootContexts ChildrenOutletContexts
location Location
injector Injector
loader NgModuleFactoryLoader
compiler Compiler
config Route[]

屬性

屬性說明
events: Observable<Event>唯讀

用於表示此 NgModule 中路由事件的事件流。

An event stream for routing events in this NgModule.

routerState: RouterState唯讀

此 NgModule 中路由的當前狀態。

The current state of routing in this NgModule.

errorHandler: ErrorHandler

本模組中的導航錯誤處理器。

A handler for navigation errors in this NgModule.

malformedUriErrorHandler: (error: URIError, urlSerializer: UrlSerializer, url: string) => UrlTree

uri 格式無效錯誤的處理器,在 Router.parseUrl(url) 由於 url 包含無效字元而報錯時呼叫。 最常見的情況可能是 % 本身既沒有被編碼,又不是正常 % 編碼序列的一部分。

A handler for errors thrown by Router.parseUrl(url) when url contains an invalid character. The most common case is a % sign that's not encoded and is not part of a percent encoded sequence.

navigated: boolean

如果為 True 則表示是否發生過至少一次導航,反之為 False。

True if at least one navigation event has occurred, false otherwise.

urlHandlingStrategy: UrlHandlingStrategy

提取併合並 URL。在 AngularJS 向 Angular 遷移時會用到。

A strategy for extracting and merging URLs. Used for AngularJS to Angular migrations.

routeReuseStrategy: RouteReuseStrategy

複用路由的策略。

A strategy for re-using routes.

onSameUrlNavigation: 'reload' | 'ignore'

定義當路由器收到一個導航到當前 URL 的請求時應該怎麼做。可取下列值之一:

How to handle a navigation request to the current URL. One of:

  • 'ignore':路由器會忽略此請求。

    'ignore' : The router ignores the request.

  • 'reload':路由器會重新載入當前 URL。用來實現"重新整理"功能。

    'reload' : The router reloads the URL. Use to implement a "refresh" feature.

paramsInheritanceStrategy: 'emptyOnly' | 'always'

如何從父路由向子路由合併引數、資料和解析到的資料。可取下列值之一:

How to merge parameters, data, and resolved data from parent to child routes. One of:

  • 'emptyOnly':讓無路徑或無元件的路由繼承父級的引數、資料和解析到的資料。

    'emptyOnly' : Inherit parent parameters, data, and resolved data for path-less or component-less routes.

  • 'always':讓所有子路由都繼承父級的引數、資料和解析到的資料。

    'always' : Inherit parent parameters, data, and resolved data for all child routes.

urlUpdateStrategy: 'deferred' | 'eager'

確定路由器何時更新瀏覽器 URL。預設情況下("deferred")在導航完成後更新瀏覽器 URL。設定為 'eager' 可以在瀏覽開始時更新瀏覽器 URL。你可以選擇早期更新,這樣,如果導航失敗,則可以顯示帶有失敗 URL 的錯誤訊息。

Determines when the router updates the browser URL. By default ("deferred"), updates the browser URL after navigation has finished. Set to 'eager' to update the browser URL at the beginning of navigation. You can choose to update early so that, if navigation fails, you can show an error message with the URL that failed.

relativeLinkResolution: 'legacy' | 'corrected'

啟用錯誤修復功能,以更正帶空路徑的元件中的相對連結。

Enables a bug fix that corrects relative link resolution in components with empty paths.

參見:

config: Routes宣告在建構函式中
url: string唯讀

當前 URL

The current URL.

方法

設定位置變化監聽器,並執行首次導航。

Sets up the location change listener and performs the initial navigation.

      
      initialNavigation(): void
    
引數

沒有引數。

返回值

void

設定 location 更改監聽器。該監聽器檢測從路由器外部觸發的導航(例如,瀏覽器的後退/前進按鈕),並安排相應的路由器導航,以便觸發正確的事件、守衛等。

Sets up the location change listener. This listener detects navigations triggered from outside the Router (the browser back/forward buttons, for example) and schedules a corresponding Router navigation so that the correct events, guards, etc. are triggered.

      
      setUpLocationChangeListener(): void
    
引數

沒有引數。

返回值

void

Returns the current Navigation object when the router is navigating, and null when idle.

      
      getCurrentNavigation(): Navigation | null
    
引數

沒有引數。

返回值

Navigation | null

重置供導航和產生連結使用的配置項。

Resets the route configuration used for navigation and generating links.

      
      resetConfig(config: Route[]): void
    
引數
config Route[]

新配置中的路由定義陣列。

The route array for the new configuration.

返回值

void

使用說明

      
      router.resetConfig([
 { path: 'team/:id', component: TeamCmp, children: [
   { path: 'simple', component: SimpleCmp },
   { path: 'user/:name', component: UserCmp }
 ]}
]);
    

銷燬路由器

Disposes of the router.

      
      dispose(): void
    
引數

沒有引數。

返回值

void

將 URL 段新增到當前 URL 樹中以建立新的 URL 樹。

Appends URL segments to the current URL tree to create a new URL tree.

      
      createUrlTree(commands: any[], navigationExtras: UrlCreationOptions = {}): UrlTree
    
引數
commands any[]

一個 URL 段的陣列,用於構造新的 URL 樹。如果此路徑是靜態的,則可能是 URL 字串字面量。對於動態路徑,可以傳入一個路徑段的陣列,後跟每個段的引數。這些段會應用到當前 URL 樹上,或者在選項物件中的 relativeTo 屬性上(如果有)。

An array of URL fragments with which to construct the new URL tree. If the path is static, can be the literal URL string. For a dynamic path, pass an array of path segments, followed by the parameters for each segment. The fragments are applied to the current URL tree or the one provided in the relativeTo property of the options object, if supplied.

navigationExtras UrlCreationOptions

控制導航策略的選項。

Options that control the navigation strategy.

可選. 預設值是 `{}`.
返回值

新的 URL Tree。

UrlTree: The new URL tree.

使用說明

      
      // create /team/33/user/11
router.createUrlTree(['/team', 33, 'user', 11]);

// create /team/33;expand=true/user/11
router.createUrlTree(['/team', 33, {expand: true}, 'user', 11]);

// you can collapse static segments like this (this works only with the first passed-in value):
router.createUrlTree(['/team/33/user', userId]);

// If the first segment can contain slashes, and you do not want the router to split it,
// you can do the following:
router.createUrlTree([{segmentPath: '/one/two'}]);

// create /team/33/(user/11//right:chat)
router.createUrlTree(['/team', 33, {outlets: {primary: 'user/11', right: 'chat'}}]);

// remove the right secondary node
router.createUrlTree(['/team', 33, {outlets: {primary: 'user/11', right: null}}]);

// assuming the current url is `/team/33/user/11` and the route points to `user/11`

// navigate to /team/33/user/11/details
router.createUrlTree(['details'], {relativeTo: route});

// navigate to /team/33/user/22
router.createUrlTree(['../22'], {relativeTo: route});

// navigate to /team/44/user/22
router.createUrlTree(['../../team/44/user/22'], {relativeTo: route});

Note that a value of `null` or `undefined` for `relativeTo` indicates that the
tree should be created relative to the root.
    

基於所提供的 URL 進行導航,必須使用絕對路徑。

Navigates to a view using an absolute route path.

See also:

      
      navigateByUrl(url: string | UrlTree, extras: NavigationBehaviorOptions = {
    skipLocationChange: false
}): Promise<boolean>
    
引數
url string | UrlTree

一個絕對 URL。該函式不會對當前 URL 做任何修改。

An absolute path for a defined route. The function does not apply any delta to the current URL.

extras NavigationBehaviorOptions

一個包含一組屬性的物件,它會修改導航策略。 該函式會忽略 NavigationExtras 中任何可能會改變所提供的 URL 的屬性

An object containing properties that modify the navigation strategy.

可選. 預設值是 `{ skipLocationChange: false }`.
返回值

一個 Promise,當導航成功時,它會解析成 true;導航失敗或出錯時,它會解析成 false

Promise<boolean>: A Promise that resolves to 'true' when navigation succeeds, to 'false' when navigation fails, or is rejected on error.

以下呼叫要求導航到絕對路徑。

The following calls request navigation to an absolute path.

      
      router.navigateByUrl("/team/33/user/11");

// Navigate without updating the URL
router.navigateByUrl("/team/33/user/11", { skipLocationChange: true });
    

基於所提供的命令陣列和起點路由進行導航。 如果沒有指定起點路由,則從根路由開始進行絕對導航。

Navigate based on the provided array of commands and a starting point. If no starting route is provided, the navigation is absolute.

See also:

      
      navigate(commands: any[], extras: NavigationExtras = { skipLocationChange: false }): Promise<boolean>
    
引數
commands any[]

一個 URL 段的陣列,用於構造目標 URL 樹。如果此路徑是靜態的,則可能是 URL 字串字面量。對於動態路徑,可以傳入一個路徑段的陣列,後跟每個段的引數。這些段會應用到當前 URL,或者在選項物件中的 relativeTo 屬性上(如果有)。

An array of URL fragments with which to construct the target URL. If the path is static, can be the literal URL string. For a dynamic path, pass an array of path segments, followed by the parameters for each segment. The fragments are applied to the current URL or the one provided in the relativeTo property of the options object, if supplied.

extras NavigationExtras

一個選項物件,用於確定應如何構造或解釋 URL。

An options object that determines how the URL should be constructed or interpreted.

可選. 預設值是 `{ skipLocationChange: false }`.
返回值

一個 Promise,在導航成功時解析為 true,導航失敗時解析為 false,或者在出錯時被拒絕。

Promise<boolean>: A Promise that resolves to true when navigation succeeds, to false when navigation fails, or is rejected on error.

以下呼叫請求導航到相對於當前 URL 的動態路由路徑。

The following calls request navigation to a dynamic route path relative to the current URL.

      
      router.navigate(['team', 33, 'user', 11], {relativeTo: route});

// Navigate without updating the URL, overriding the default behavior
router.navigate(['team', 33, 'user', 11], {relativeTo: route, skipLocationChange: true});
    

UrlTree 序列化為字串

Serializes a UrlTree into a string

      
      serializeUrl(url: UrlTree): string
    
引數
url UrlTree
返回值

string

把字串解析為 UrlTree

Parses a string into a UrlTree

      
      parseUrl(url: string): UrlTree
    
引數
url string
返回值

UrlTree

3 個過載形式...

顯示所有 隱藏所有 expand_more
Overload #1

Returns whether the url is activated.

      
      isActive(url: string | UrlTree, exact: boolean): boolean
    

Deprecated Use IsActiveUrlTreeOptions instead.

  • The equivalent IsActiveUrlTreeOptions for true is {paths: 'exact', queryParams: 'exact', fragment: 'ignored', matrixParams: 'ignored'}.
  • The equivalent for false is {paths: 'subset', queryParams: 'subset', fragment: 'ignored', matrixParams: 'ignored'}.
引數
url string | UrlTree
exact boolean
返回值

boolean


Overload #2

Returns whether the url is activated.

      
      isActive(url: string | UrlTree, matchOptions: IsActiveMatchOptions): boolean
    
引數
url string | UrlTree
matchOptions IsActiveMatchOptions
返回值

boolean


Overload #3
      
      isActive(url: string | UrlTree, matchOptions: boolean | IsActiveMatchOptions): boolean
    
引數
url string | UrlTree
matchOptions boolean | IsActiveMatchOptions
返回值

boolean