Router

Provides the navigation and url manipulation capabilities.

提供导航和操纵 URL 的能力。

class Router { constructor(rootComponentType: Type<any> | null, urlSerializer: UrlSerializer, rootContexts: ChildrenOutletContexts, location: Location, injector: Injector, loader: NgModuleFactoryLoader, compiler: Compiler, config: Routes) get events: Observable<Event> get 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 get url: string initialNavigation(): void setUpLocationChangeListener(): void resetConfig(config: Routes): void ngOnDestroy(): void dispose(): void createUrlTree(commands: any[], navigationExtras: NavigationExtras = {}): UrlTree navigateByUrl(url: string | UrlTree, extras: NavigationExtras = { skipLocationChange: false }): Promise<boolean> navigate(commands: any[], extras: NavigationExtras = { skipLocationChange: false }): Promise<boolean> serializeUrl(url: UrlTree): string parseUrl(url: string): UrlTree isActive(url: string | UrlTree, exact: boolean): boolean }

说明

See Routes for more details and examples.

查看 Routes 以了解详情和范例。

构造函数

Creates the router service.

创建路由器服务。

constructor(rootComponentType: Type<any> | null, urlSerializer: UrlSerializer, rootContexts: ChildrenOutletContexts, location: Location, injector: Injector, loader: NgModuleFactoryLoader, compiler: Compiler, config: Routes)

参数

rootComponentType

Type: Type | null.

urlSerializer

Type: UrlSerializer.

rootContexts

Type: ChildrenOutletContexts.

location

Type: Location.

injector

Type: Injector.

loader

Type: NgModuleFactoryLoader.

compiler

Type: Compiler.

config

Type: Routes.

属性

属性名类型说明
events只读
routerState只读
errorHandler

Error handler that is invoked when a navigation errors.

当导航发生错误时要调用的错误处理器。

See ErrorHandler for more information.

欲知详情,参见 ErrorHandler

malformedUriErrorHandler

Malformed uri error handler is invoked when Router.parseUrl(url) throws an error due to containing an invalid character. The most common case would be a % sign that's not encoded and is not part of a percent encoded sequence.

uri 格式无效错误的处理器,在 Router.parseUrl(url) 由于 url 包含无效字符而报错时调用。 最常见的情况可能是 % 本身既没有被编码,又不是正常 % 编码序列的一部分。

navigated

Indicates if at least one navigation happened.

表示是否发生过至少一次导航。

urlHandlingStrategy

Extracts and merges URLs. Used for AngularJS to Angular migrations.

提取并合并 URL。在 AngularJS 向 Angular 迁移时会用到。

routeReuseStrategy
onSameUrlNavigation

Define what the router should do if it receives a navigation request to the current URL. By default, the router will ignore this navigation. However, this prevents features such as a "refresh" button. Use this option to configure the behavior when navigating to the current URL. Default is 'ignore'.

定义当路由器收到一个导航到当前 URL 的请求时应该怎么做。 默认情况下,路由器将会忽略这次导航。但这样会阻止类似于 "刷新" 按钮的特性。 使用该选项可以配置导航到当前 URL 时的行为。默认值为 'ignore'。

paramsInheritanceStrategy

Defines how the router merges params, data and resolved data from parent to child routes. Available options are:

定义路由器如何从父路由向子路由合并参数、数据。可用选项为:

  • 'emptyOnly', the default, only inherits parent params for path-less or component-less routes.

    'emptyOnly',默认值,只从无路径或无组件的路由继承父级参数。

  • 'always', enables unconditional inheritance of parent params.

    'always',允许无条件地继承父级参数。

urlUpdateStrategy

Defines when the router updates the browser URL. The default behavior is to update after successful navigation. However, some applications may prefer a mode where the URL gets updated at the beginning of navigation. The most common use case would be updating the URL early so if navigation fails, you can show an error message with the URL that failed. Available options are:

定义路由器要何时更新浏览器的 URL。默认行为是在每次成功的导航之后更新。 不过,有些应用会更愿意在导航开始时就更新。最常见的情况是尽早更新 URL,这样当导航失败时,你就可以在出错的 URL 上显示一条错误信息了。 可用的选项包括:

  • 'deferred', the default, updates the browser URL after navigation has finished.

    'deferred',默认值,在导航完毕后更新浏览器 URL。

  • 'eager', updates browser URL at the beginning of navigation.

    'eager',在导航开始时更新浏览器的 URL。

relativeLinkResolution

See RouterModulefor more information.

欲知详情,参见 RouterModule

config声明于构造函数中
url只读

The current url

当前 URL

方法

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

设置位置变化监听器,并执行首次导航。

initialNavigation(): void

参数

没有参数。

返回值

void

Sets up the location change listener.

设置位置变化监听器。

setUpLocationChangeListener(): void

参数

没有参数。

返回值

void

Resets the configuration used for navigation and generating links.

重置供导航和生成链接使用的配置项。

resetConfig(config: Routes): void

参数

config

Type: Routes.

返回值

void

Usage

用法

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

参数

没有参数。

返回值

void

Disposes of the router

销毁路由器

dispose(): void

参数

没有参数。

返回值

void

Applies an array of commands to the current url tree and creates a new url tree.

把一个命令数组应用于当前的 URL 树,并创建一个新的 URL 树。

createUrlTree(commands: any[], navigationExtras: NavigationExtras = {}): UrlTree

参数

commands

Type: any[].

navigationExtras

Type: NavigationExtras.

可选. 默认值是 {}.

返回值

UrlTree

When given an activate route, applies the given commands starting from the route. When not given a route, applies the given command starting from the root.

如果指定了激活路由,就以该路由为起点应用这些命令。 如果没有指定激活路由,就以根路由为起点应用这些命令。

Usage

用法

// 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});

Navigate based on the provided url. This navigation is always absolute.

基于所提供的 url 进行导航。这种导航永远使用绝对路径。

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

参数

url

Type: string | UrlTree.

extras

Type: NavigationExtras.

可选. 默认值是 { skipLocationChange: false }.

返回值

Promise<boolean>

Returns a promise that:

返回一个 Promise:

  • resolves to 'true' when navigation succeeds,

    当导航成功时解析为 'true'

  • resolves to 'false' when navigation fails,

    当导航失败时解析为 'false'

  • is rejected when an error happens.

    当出错时拒绝(reject)。

Usage

用法

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

In opposite to navigate, navigateByUrl takes a whole URL and does not apply any delta to the current one.

navigate 不同,navigateByUrl 只接收完整的 URL,而不会管当前 URL。

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

基于所提供的命令数组和起点路由进行导航。 如果没有指定起点路由,则从根路由开始进行绝对导航。

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

参数

commands

Type: any[].

extras

Type: NavigationExtras.

可选. 默认值是 { skipLocationChange: false }.

返回值

Promise<boolean>

Returns a promise that:

返回一个 Promise:

  • resolves to 'true' when navigation succeeds,

    当导航成功时解析为 'true'

  • resolves to 'false' when navigation fails,

    当导航失败时解析为 'false'

  • is rejected when an error happens.

    当出错时拒绝(reject)。

Usage

用法

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

In opposite to navigateByUrl, navigate always takes a delta that is applied to the current URL.

Serializes a UrlTree into a string

UrlTree 序列化为字符串

serializeUrl(url: UrlTree): string

参数

url

Type: UrlTree.

返回值

string

Parses a string into a UrlTree

把字符串解析为 UrlTree

parseUrl(url: string): UrlTree

参数

url

Type: string.

返回值

UrlTree

Returns whether the url is activated

返回指定的 url 是否处于激活状态

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

参数

url

Type: string | UrlTree.

exact

Type: boolean.

返回值

boolean