填寫這份《一分鐘調查》,幫我們(開發組)做得更好!去填寫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.