Different RouterModule configurations for same URL

旧巷老猫 提交于 2019-12-08 03:38:42

问题


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:


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.



来源:https://stackoverflow.com/questions/39873452/different-routermodule-configurations-for-same-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!