Angular2 router (@angular/router), how to set default route?

后端 未结 10 2019
广开言路
广开言路 2020-12-02 15:07

How can I set a default route in my @Routes route metadata collection? If you use the angular2 router from @angular/router-deprecated you define the routes in @routeConfig

10条回答
  •  心在旅途
    2020-12-02 15:43

    V2.0.0 and later

    See also see https://angular.io/guide/router#the-default-route-to-heroes

    RouterConfig = [
      { path: '', redirectTo: '/heroes', pathMatch: 'full' },
      { path: 'heroes', component: HeroComponent,
        children: [
          { path: '', redirectTo: '/detail', pathMatch: 'full' },
          { path: 'detail', component: HeroDetailComponent }
        ] 
      }
    ];
    

    There is also the catch-all route

    { path: '**', redirectTo: '/heroes', pathMatch: 'full' },
    

    which redirects "invalid" urls.

    V3-alpha (vladivostok)

    Use path / and redirectTo

    RouterConfig = [
      { path: '/', redirectTo: 'heroes', terminal: true },
      { path: 'heroes', component: HeroComponent,
        children: [
          { path: '/', redirectTo: 'detail', terminal: true },
          { path: 'detail', component: HeroDetailComponent }
        ] 
      }
    ];
    

    RC.1 @angular/router

    The RC router doesn't yet support useAsDefault. As a workaround you can navigate explicitely.

    In the root component

    export class AppComponent {
      constructor(router:Router) {
        router.navigate(['/Merge']);
      }
    }
    

    for other components

    export class OtherComponent {
      constructor(private router:Router) {}
    
      routerOnActivate(curr: RouteSegment, prev?: RouteSegment, currTree?: RouteTree, prevTree?: RouteTree) : void {
        this.router.navigate(['SomeRoute'], curr);
      }
    }
    

提交回复
热议问题