ExtraOptions

表示路由器的配置项。

Represents options to configure the router.

      
      
  1. interface ExtraOptions {
  2. enableTracing?: boolean
  3. useHash?: boolean
  4. initialNavigation?: InitialNavigation
  5. errorHandler?: ErrorHandler
  6. preloadingStrategy?: any
  7. onSameUrlNavigation?: 'reload' | 'ignore'
  8. scrollPositionRestoration?: 'disabled' | 'enabled' | 'top'
  9. anchorScrolling?: 'disabled' | 'enabled'
  10. scrollOffset?: [number, number] | (() => [number, number])
  11. paramsInheritanceStrategy?: 'emptyOnly' | 'always'
  12. malformedUriErrorHandler?: (error: URIError, urlSerializer: UrlSerializer, url: string) => UrlTree
  13. urlUpdateStrategy?: 'deferred' | 'eager'
  14. relativeLinkResolution?: 'legacy' | 'corrected'
  15. }

属性

属性说明
enableTracing?: boolean

让路由器将其所有的内部事件都记录到控制台中。

Makes the router log all its internal events to the console.

useHash?: boolean

修改位置策略(LocationStrategy),用 URL 片段(#)代替 history API。

Enables the location strategy that uses the URL fragment instead of the history API.

initialNavigation?: InitialNavigation

禁用首次导航

Disables the initial navigation.

errorHandler?: ErrorHandler

自定义的错误处理器。

A custom error handler.

preloadingStrategy?: any

配置预加载策略,参见 PreloadAllModules

Configures a preloading strategy. See PreloadAllModules.

onSameUrlNavigation?: 'reload' | 'ignore'

规定当路由器收到一个导航到当前 URL 的请求时该如何处理。 默认情况下,路由器会忽略本次导航。不过,这会阻止实现类似于"刷新"按钮的功能。 使用该选项可以控制导航到当前 URL 时的行为。默认为 'ignore'。

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'.

scrollPositionRestoration?: 'disabled' | 'enabled' | 'top'

配置是否需要在导航回来的时候恢复滚动位置。

Configures if the scroll position needs to be restored when navigating back.

  • 'disabled' - 什么也不做(默认)。

    'disabled'--does nothing (default).

  • 'top' - 把滚动位置设置为 0,0。

    'top'--set the scroll position to 0,0..

  • 'enabled' - 把滚动位置设置为以前保存的位置。将来这个选项会变成默认值。

    'enabled'--set the scroll position to the stored position. This option will be the default in the future.

当启用时,路由器会在导航时保存和恢复滚动位置。当向前导航时,滚动位置会设置为 [0, 0],如果指定了锚点,则跳转到那个锚点。

When enabled, the router stores and restores scroll positions during navigation. When navigating forward, the scroll position will be set to [0, 0], or to the anchor if one is provided.

你可以自定义滚动位置的恢复策略。

You can implement custom scroll restoration behavior as follows.

class AppModule { constructor(router: Router, viewportScroller: ViewportScroller, store: Store<AppState>) { router.events.pipe(filter(e => e instanceof Scroll), switchMap(e => { return store.pipe(first(), timeout(200), map(() => e)); }).subscribe(e => { if (e.position) { viewportScroller.scrollToPosition(e.position); } else if (e.anchor) { viewportScroller.scrollToAnchor(e.anchor); } else { viewportScroller.scrollToPosition([0, 0]); } }); } }
      
      
  1. class AppModule {
  2. constructor(router: Router, viewportScroller: ViewportScroller, store: Store<AppState>) {
  3. router.events.pipe(filter(e => e instanceof Scroll), switchMap(e => {
  4. return store.pipe(first(), timeout(200), map(() => e));
  5. }).subscribe(e => {
  6. if (e.position) {
  7. viewportScroller.scrollToPosition(e.position);
  8. } else if (e.anchor) {
  9. viewportScroller.scrollToAnchor(e.anchor);
  10. } else {
  11. viewportScroller.scrollToPosition([0, 0]);
  12. }
  13. });
  14. }
  15. }

你还可以像这样在组件级实现滚动位置恢复策略:

You can also implement component-specific scrolling like this:

class ListComponent { list: any[]; constructor(router: Router, viewportScroller: ViewportScroller, fetcher: ListFetcher) { const scrollEvents = router.events.filter(e => e instanceof Scroll); listFetcher.fetch().pipe(withLatestFrom(scrollEvents)).subscribe(([list, e]) => { this.list = list; if (e.position) { viewportScroller.scrollToPosition(e.position); } else { viewportScroller.scrollToPosition([0, 0]); } }); } }
      
      
  1. class ListComponent {
  2. list: any[];
  3. constructor(router: Router, viewportScroller: ViewportScroller, fetcher: ListFetcher) {
  4. const scrollEvents = router.events.filter(e => e instanceof Scroll);
  5. listFetcher.fetch().pipe(withLatestFrom(scrollEvents)).subscribe(([list, e]) => {
  6. this.list = list;
  7. if (e.position) {
  8. viewportScroller.scrollToPosition(e.position);
  9. } else {
  10. viewportScroller.scrollToPosition([0, 0]);
  11. }
  12. });
  13. }
  14. }
anchorScrolling?: 'disabled' | 'enabled'

配置当 url 中带有片段(#)时路由器是否滚动到那个元素。

Configures if the router should scroll to the element when the url has a fragment.

  • 'disabled' - 什么也不做(默认)。

    'disabled'--does nothing (default).

  • 'enabled' - 滚动到该元素。将来该选项会变为默认值。

    'enabled'--scrolls to the element. This option will be the default in the future.

在 'popstate' 时,不会自动滚动到锚点,而是恢复应用中保存的滚动位置,或滚动到顶部。

Anchor scrolling does not happen on 'popstate'. Instead, we restore the position that we stored or scroll to the top.

scrollOffset?: [number, number] | (() => [number, number])

配置当滚动到一个元素时,路由器使用的滚动偏移。

Configures the scroll offset the router will use when scrolling to an element.

当给出两个数字时,路由器总会使用它们。 当给出一个函数时,路由器每当要恢复滚动位置时,都会调用该函数。

When given a tuple with two numbers, the router will always use the numbers. When given a function, the router will invoke the function every time it restores scroll position.

paramsInheritanceStrategy?: 'emptyOnly' | 'always'

定义路由器如何把父路由的参数、数据和解析出的数据合并到子路由。有效的选项包括:

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

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

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

  • 'always',无条件继承父路由的参数。

    'always', enables unconditional inheritance of parent params.

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

一个自定义的 URI 格式无效错误的处理器。每当 encodeURI 包含无效字符序列时,就会调用该处理器。默认的实现是跳转到根路径,抛弃任何路径和参数信息。该函数传入三个参数:

A custom malformed uri error handler function. This handler is invoked when encodedURI contains invalid character sequences. The default implementation is to redirect to the root url dropping any path or param info. This function passes three parameters:

  • 'URIError' - 当传入错误的 URL 时抛出的错误

    'URIError' - Error thrown when parsing a bad URL

  • 'UrlSerializer' - 路由器所配置的 UrlSerializer。

    'UrlSerializer' - UrlSerializer that’s configured with the router.

  • 'url' - 导致 URIError 的格式无效的 URL

    'url' - The malformed URL that caused the URIError

urlUpdateStrategy?: 'deferred' | 'eager'

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

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:

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

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

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

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

relativeLinkResolution?: 'legacy' | 'corrected'

启用 BUG 补丁,纠正空路径组件的相对链接解析问题。

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

const routes = [ { path: '', component: ContainerComponent, children: [ { path: 'a', component: AComponent }, { path: 'b', component: BComponent }, ] } ];
      
      const routes = [
  {
    path: '',
    component: ContainerComponent,
    children: [
      { path: 'a', component: AComponent },
      { path: 'b', component: BComponent },
    ]
  }
];
    

ContainerComponent 中不能这样用:

From the ContainerComponent, this will not work:

<a [routerLink]="['./a']">Link to A</a>

不过,可以这样用:

However, this will work:

<a [routerLink]="['../a']">Link to A</a>

换句话说,要使用 ../ 而不是 ./。目前 v6 版本的默认值是 legacy,到 v7 就会移除该选项,以纠正此行为。

In other words, you're required to use ../ rather than ./. The current default in v6 is legacy, and this option will be removed in v7 to default to the corrected behavior.