填写这份《一分钟调查》,帮我们(开发组)做得更好!去填写Home

ExtraOptions

forRoot() 方法中提供的一组路由器模块配置选项。

A set of configuration options for a router module, provided in the forRoot() method.

      
      interface ExtraOptions {
  enableTracing?: boolean
  useHash?: boolean
  initialNavigation?: InitialNavigation
  errorHandler?: ErrorHandler
  preloadingStrategy?: any
  onSameUrlNavigation?: 'reload' | 'ignore'
  scrollPositionRestoration?: 'disabled' | 'enabled' | 'top'
  anchorScrolling?: 'disabled' | 'enabled'
  scrollOffset?: [number, number] | (() => [number, number])
  paramsInheritanceStrategy?: 'emptyOnly' | 'always'
  malformedUriErrorHandler?: (error: URIError, urlSerializer: UrlSerializer, url: string) => UrlTree
  urlUpdateStrategy?: 'deferred' | 'eager'
  relativeLinkResolution?: 'legacy' | 'corrected'
}
    

参见

  • forRoot()

属性

属性说明
enableTracing?: boolean

如果为 true,则将所有内部导航事件记录到控制台。用于调试。

When true, log all internal navigation events to the console. Use for debugging.

useHash?: boolean

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

When true, enable the location strategy that uses the URL fragment instead of the history API.

initialNavigation?: InitialNavigation

enabledenabledBlockingenabledNonBlockingdisabled 之一。 设置为 enabledenabledBlocking ,则初始导航在创建根组件之前开始。引导程序将被阻止,直到完成初始导航为止。 该值是让服务器端渲染正常工作所必需的。 设置为 enabledNonBlocking,则初始导航在创建根组件之后开始。初始导航完成后,引导程序不会被阻止。 设置为 disabled,不执行初始导航。位置监听器是在创建根组件之前设置的。 如果由于某些复杂的初始化逻辑,而有理由对路由器何时开始其初始导航有更多的控制权,请使用它。

One of enabled, enabledBlocking, enabledNonBlocking or disabled. When set to enabled or enabledBlocking, the initial navigation starts before the root component is created. The bootstrap is blocked until the initial navigation is complete. This value is required for server-side rendering to work. When set to enabledNonBlocking, the initial navigation starts after the root component has been created. The bootstrap is not blocked on the completion of the initial navigation. When set to disabled, the initial navigation is not performed. The location listener is set up before the root component gets created. Use if there is a reason to have more control over when the router starts its initial navigation due to some complex initialization logic.

errorHandler?: ErrorHandler

导航失败的自定义错误处理器。如果处理器返回一个值,则导航的 Promise 将使用该值进行解析。如果处理器引发异常,则导航 Promise 将被拒绝,并带有该异常。

A custom error handler for failed navigations. If the handler returns a value, the navigation Promise is resolved with this value. If the handler throws an exception, the navigation Promise is rejected with the exception.

preloadingStrategy?: any

配置预加载策略,参见 PreloadAllModules

Configures a preloading strategy. One of PreloadAllModules or NoPreloading (the default).

onSameUrlNavigation?: 'reload' | 'ignore'

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

Define what the router should do if it receives a navigation request to the current URL. Default is ignore, which causes the router ignores the navigation. This can disable 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'- (Default) Does nothing. Scroll position is maintained on navigation.

  • 'top' - 在任何一次导航中都把滚动位置设置为 x=0, y=0。

    'top'- Sets the scroll position to x = 0, y = 0 on all navigation.

  • 'enabled' —— 当向后导航时,滚动到以前的滚动位置。当向前导航时,如果提供了锚点,则自动滚动到那个锚点,否则把滚动位置设置为 [0, 0]。该选项将来会变成默认值。

    'enabled'- Restores the previous scroll position on backward navigation, else sets the position to the anchor if one is provided, or sets the scroll position to [0, 0] (forward navigation). This option will be the default in the future.

你可以像下面的例子一样适配它启用时的行为,来自定义恢复滚动位置的策略:

You can implement custom scroll restoration behavior by adapting the enabled behavior as in the following example.

      
      class AppModule {
  constructor(router: Router, viewportScroller: ViewportScroller) {
    router.events.pipe(
      filter((e: Event): e is Scroll => e instanceof Scroll)
    ).subscribe(e => {
      if (e.position) {
        // backward navigation
        viewportScroller.scrollToPosition(e.position);
      } else if (e.anchor) {
        // anchor navigation
        viewportScroller.scrollToAnchor(e.anchor);
      } else {
        // forward navigation
        viewportScroller.scrollToPosition([0, 0]);
      }
    });
  }
}
    
anchorScrolling?: 'disabled' | 'enabled'

设置为 “enabled” 时,如果 URL 有一个片段,就滚动到锚点元素。默认情况下,锚定滚动是禁用的。

When set to 'enabled', scrolls to the anchor element when the URL has a fragment. Anchor scrolling is disabled by default.

锚点滚动不会在 “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 x and y position value, the router uses that offset each time it scrolls. When given a function, the router invokes the function every time it restores scroll position.

paramsInheritanceStrategy?: 'emptyOnly' | 'always'

定义路由器如何将参数、数据和已解析的数据从父路由合并到子路由。默认情况下(“emptyOnly”),仅继承无路径或无组件路由的父参数。

Defines how the router merges parameters, data, and resolved data from parent to child routes. By default ('emptyOnly'), inherits parent parameters only for path-less or component-less routes.

设置为 “always” 时会始终启用父参数的无条件继承。

Set to 'always' to enable unconditional inheritance of parent parameters.

Note that when dealing with matrix parameters, "parent" refers to the parent Route config which does not necessarily mean the "URL segment to the left". When the Route path contains multiple segments, the matrix parameters must appear on the last segment. For example, matrix parameters for {path: 'a/b', component: MyComp} should appear as a/b;foo=bar and not a;foo=bar/b.

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

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

A custom handler for malformed URI errors. The handler is invoked when encodedURI contains invalid character sequences. The default implementation is to redirect to the root URL, dropping any path or parameter information. The function takes 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。默认情况下(“deferred”),在成功导航后进行更新。如果希望在导航开始时更新 URL,则设置为 “eager” 。 以便早期更新 URL,这样可以通过显示带有失败 URL 的错误消息来处理导航失败。

Defines when the router updates the browser URL. By default ('deferred'), update after successful navigation. Set to 'eager' if prefer to update the URL at the beginning of navigation. Updating the URL early allows you to handle a failure of navigation by showing an error message with the URL that failed.

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 },
    ]
  }
];
    

ContainerComponent 中不能这样用:

From the ContainerComponent, you should be able to navigate to AComponent using the following routerLink, but it will not work if relativeLinkResolution is set to 'legacy':

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

不过,可以这样用:

However, this will work:

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

换句话说,你需要使用 ../ 而不是 ./

In other words, you're required to use ../ rather than ./ when the relative link resolution is set to 'legacy'.

v11 中的默认值是 corrected

The default in v11 is corrected.