Different RouterModule configurations for same URL

2019-06-06 05:50发布

Consider this code:

@NgModule({
  imports: [RouterModule.forRoot([

    { path: 'about', component: AboutComponent },

    { path: '', loadChildren: 'app/admin.module#AdminModule', canLoad: [AuthGuard] },
    { path: '', component: HomeComponent, canActivate: [HomeGuard] },

  ])],
  providers: [
    AuthGuard, // return true if user is Authorized 
    HomeGuard  // return true if user is NOT Authorized
  ]
})
export class AppRoutingModule { }

@NgModule({
  imports: [RouterModule.forChild([

    { path: '', component: DashboardComponent, canActivate: [AuthGuard] },
    { path: 'account', component: AccountComponent, canActivate: [AuthGuard] },

  ])],
  providers: [
    AuthGuard, // return true if user is Authorized 
  ]
})
export class AdminModule { }

When I listen to Router events with: this.router.events.subscribe(console.log); (if I'm NOT authorized) I can see NavigationCancel event with message:

"Cannot load children because the guard of the route "path: ''" returned false"

If I am authorized RoutesRecognized event is fired, as expected.

As I understand it, Router goes through provided routes and tries to recognize active one. If it does recognize the route, it then checks guards, loads components, etc.

My question is: HOW Router recognizes specific route?

Is it by path/url only? Or does it consider any other parameters?

Is there another solution for this (other then renaming path for HomeComponent)?

1条回答
趁早两清
2楼-- · 2019-06-06 06:22

The router just compares the url with the path parameters of the routes of the configurations.

It takes the first root route where the start of the url matches, then it continues with the child routes of the matching root route with the remaining part of the url (the url where the path of the matching root route was removed at the beginning). This is continued until the remaining URL is empty and no child routes with path: '' (empty path) exist.

A way would be to reconfigure the router (resetConfig()) for example when AuthGuard returns true.

查看更多
登录 后发表回答