ForRoot (Routes: Route[], config? : ExtraOptions) in config

First, what is the ExtraOptions interface

interfaceExtraOptions { enableTracing? :booleanuseHash? :booleaninitialNavigation? : InitialNavigation errorHandler? : ErrorHandler preloadingStrategy? :anyonSameUrlNavigation? :'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'
}
Copy the code
  1. EnableTracing is a Boolean that, when configured to true, logs internal navigation events to the console

    const routes: Routes = [
      { path: 'first-component'.component: FirstComponent },
      { path: 'second-component'.component: SecondComponent },
    ];
    
    @NgModule({
      imports: [RouterModule.forRoot(routes,{
        enableTracing: true})].exports: [RouterModule]
    })
    export class AppRoutingModule {}Copy the code
    <! -- Component elision -->
    <div>
        <a nz-button routerLink="/first-component" routerLinkActive="active">The component a</a> &nbsp;
        <a nz-button routerLink="/second-component" routerLinkActive="active">Component 2</a>
    </div>
    Copy the code

    The figure above clearly shows the sequence of events triggered during the navigation process

  2. UseHash: Boolean change the location policy, use URL fragment (#) instead of the history API, useHash mode or use history mode, default is false, use history mode

  3. InitialNavigation sets whether navigation starts before or after AppComponent creation. Default is enabledNonBlocking: initialNavigation starts after root component creation and the bootstrap is not blocked. EnabledBlocking: Initial navigation starts before the root component is created, the bootstrap will be blocked, and this value is required for server rendering to work properly.

  4. ErrorHandler user-defined errorHandler for navigation failure. When routing errors occur, you can catch them

    1. If no error is caught, the following error is reported if the route fails to match

    2. Customize error handlers

    // Customize ErrorHandle
    class MyErrorHandler implements ErrorHandler {
      handleError(error: any) {
        console.warn('You can customize error handlers when routing errors occur')}}// App.module.ts
    @NgModule({...providers: [{provide: ErrorHandler, useClass: MyErrorHandler } // Declare a token so that you can implement your own route error handlers],... })Copy the code
  5. PreloadingStrategy configures a preloadingStrategy to preload all modules as soon as the program is idle.

    1. When you need to use this preloadingStrategy, you simply configure the preloadingStrategy in routermodule. forRoot

      @NgModule({
        imports: [RouterModule.forRoot(routes, {
          preloadingStrategy: PreloadAllModules
        })]
      })
      Copy the code

    2. You can also customize the preloading mode, such as loading preloaded modules 3 seconds after the application finishes loading

      // app-routing.module.ts
      const routes: Routes = [
        { path: 'first-component'.component: FirstComponent },
        { path: 'second-component'.component: SecondComponent },
        { 
          path: 'load'.loadChildren: () = > import('./load/load.module').then(m= > m.LoadModule),
          data: {
            preload: true // Use preload in data as an indicator to determine whether to use PreloadAllModules mode}, {},path: 'home'.loadChildren: () = > import('./home/home.module').then(m= > m.HomeModule),
          data: {
            preload: true.// Use preload in data as an indicator to determine whether to use PreloadAllModules mode
            delay: 3000 // Load after 3000 milliseconds, or immediately if the currently accessed route is page under the home module}},];// app.module.ts 
      class ServicePreloadingStrategy implements PreloadingStrategy {
        preload(route: Route, load: () = > import("rxjs").Observable<any>): Observable<any> {
          return route.data && route.data.preload ? timer(route.data.delay || 0).pipe(
            mergeMap(() = > load())
          )
          : of(null); }}// The home module will load the corresponding module 3 seconds after the program finishes running
      @NgModule({...providers: [{provide: PreloadingStrategy, useClass: ServicePreloadingStrategy },
        ],
        ...
      })
          
      Copy the code
  6. What if onSameUrlNavigation navigates requests to the current URL. This navigation is ignored by default, but not if you’re doing a refresh

    1. Two modes, ignore by default and navigation will not be ignored when you set it to Reload

      @NgModule({...imports: [RouterModule.forRoot(routes, {
          onSameUrlNavigation: 'reload' // Use reload mode, ignore by default})],... })export class HomePageComponent implements OnInit {
        constructor(
          private router: Router,
          private route: ActivatedRoute
        ) {
          this.route.url.subscribe(console.log) // After using Reload mode, call the goSelf method and the URL will be subscribed to the value again
          // If you set enableTracing: true, you can again see the full cycle of the function when a URL jump is triggered.
         }
        goSelf(){
          this.router.navigateByUrl('/home/home-page')}}Copy the code
  7. ScrollPositionRestoration configuration is needed in the navigation back to restore scroll position

    1. The default is disabled to do nothing, and each time top navigates back, the scroll position is set to x=0, y=0. Enabled When navigating backwards, scroll to the previous scroll position

    2. If you want to navigate back, scroll to the last location

      @NgModule({...imports: [RouterModule.forRoot(routes, {
          scrollPositionRestoration: 'enabled' // Restore the last scroll position})],... })Copy the code
    3. You can customize the recovery scrolling strategy

      export class AppComponent {
        constructor(
          private router: Router,
          viewportScroller: ViewportScroller
        ){
          this.router.events.pipe(
            filter(e= > e instanceof Scroll)
          ).subscribe(route= >{
            route = route as Scroll;
            if (route.position){
              viewportScroller.scrollToPosition(route.position) // Route remembers the position it left the last time it navigated. When it navigates back again, it can set the scrollbar to the remembered position
            }else if(route.anchor){
              viewportScroller.scrollToAnchor(route.anchor)
            }else{
              viewportScroller.scrollToPosition([0.0])}})}}Copy the code
  8. AnchorScrolling scrolling to the anchor element if the URL has a segment

    1. Navigate back and scroll to the specified element

    2. Default disabled disables scrolling to anchors, but if you set enabled you can scroll to the specified element

      @NgModule({
        imports: [RouterModule.forRoot(routes, {
          anchorScrolling: 'enabled',})],... })// home-page.component.ts
      export class HomePageComponent implements OnInit {
        constructor(
          private router: Router
        ){}goSelf(){
          this.router.navigate(['home'.'home-page'] and {fragment: 'top'}}})Copy the code
      <! -- home-Page -> <div class="home-page"> <button NZ-Button (click)="goSelf()"> Jump to yourself </button><br/> <a [routerLink] = "['/home/home - page]" fragments = "top" > to jump to his < / a > < h1 id = "top" > target element < / h1 > < / div >Copy the code
  9. ScrollOffset configures the scrollOffset used by the router when scrolling to an element

    1. It is typically used in combination with the above anchorScrolling, which scrolls to the specified element and then offsets it

        imports: [RouterModule.forRoot(routes, {
          anchorScrolling: 'enabled'.scrollOffset: [0.100] // Offset 100px down})].Copy the code
  10. ParamsInheritanceStrategy defining how the router will parameters, data, and the parsed data from routing merged into the father zi lu by

    1. By default emptyOnly inherits the parent argument of a pathless or componentless route, for example

      const routes: Routes = [
        {
          path: 'second-component/:pid'.component: SecondComponent,
          children: [{path: ' '.component: SecondIndexComponent}, // The pathless route is merged into the child route
            { path: 'child'.component: SecondChildComponent}, // If there are paths, child paths cannot be merged]]},Copy the code
    2. The always option always enables unconditional inheritance of parent arguments

      // When we want pid parameters in SecondChildComponent, we need to set always
      @NgModule({
        imports: [RouterModule.forRoot(routes, {
          paramsInheritanceStrategy: 'always'})],exports: [RouterModule]
      })
      
      // second-child.component.ts
      export class SecondChildComponent implements OnInit {
        constructor(
          private route: ActivatedRoute
        ) { }
      
        ngOnInit(): void {
          console.log('params'.this.route.snapshot.params); // Set 'always' to get pid}}Copy the code