填写这份《一分钟调查》,帮我们(开发组)做得更好!去填写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: Routes) 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: Routes): 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, exact: boolean): boolean }
      
      class Router {
  constructor(rootComponentType: Type<any>, urlSerializer: UrlSerializer, rootContexts: ChildrenOutletContexts, location: Location, injector: Injector, loader: NgModuleFactoryLoader, compiler: Compiler, config: Routes)
  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: Routes): 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, exact: boolean): boolean
}
    

参见

构造函数

创建路由器服务。

Creates the router service.

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

属性

属性说明
events: Observable<Event>只读

An event stream for routing events in this NgModule.

routerState: RouterState只读

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'

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: RoutesDeclared in constructor.
url: string只读

当前 URL

The current URL.

方法

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

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

initialNavigation(): void
      
      initialNavigation(): void
    
参数

没有参数。

返回值

void

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
      
      setUpLocationChangeListener(): void
    
参数

没有参数。

返回值

void

The current Navigation object if one exists

getCurrentNavigation(): Navigation | null
      
      getCurrentNavigation(): Navigation | null
    
参数

没有参数。

返回值

Navigation | null

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

Resets the route configuration used for navigation and generating links.

resetConfig(config: Routes): void
      
      resetConfig(config: Routes): void
    
参数
config Routes

新配置中的路由定义数组。

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 } ]} ]);
      
      router.resetConfig([
 { path: 'team/:id', component: TeamCmp, children: [
   { path: 'simple', component: SimpleCmp },
   { path: 'user/:name', component: UserCmp }
 ]}
]);
    

销毁路由器

Disposes of the router.

dispose(): void
      
      dispose(): void
    
参数

没有参数。

返回值

void

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

createUrlTree(commands: any[], navigationExtras: UrlCreationOptions = {}): UrlTree
      
      createUrlTree(commands: any[], navigationExtras: UrlCreationOptions = {}): UrlTree
    
参数
commands any[]

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

基于所提供的 URL 进行导航,必须使用绝对路径。

Navigates to a view using an absolute route path.

See also:

navigateByUrl(url: string | UrlTree, extras: NavigationBehaviorOptions = { skipLocationChange: false }): Promise<boolean>
      
      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 });
      
      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>
      
      navigate(commands: any[], extras: NavigationExtras = { skipLocationChange: false }): Promise<boolean>
    
参数
commands any[]

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

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

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

返回值

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 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});
      
      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
      
      serializeUrl(url: UrlTree): string
    
参数
url UrlTree
返回值

string

把字符串解析为 UrlTree

Parses a string into a UrlTree

parseUrl(url: string): UrlTree
      
      parseUrl(url: string): UrlTree
    
参数
url string
返回值

UrlTree

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

Returns whether the url is activated

isActive(url: string | UrlTree, exact: boolean): boolean
      
      isActive(url: string | UrlTree, exact: boolean): boolean
    
参数
url string | UrlTree
exact boolean
返回值

boolean