相同 URL 的不同 RouterModule 配置 [英] Different RouterModule configurations for same URL

查看:31
本文介绍了相同 URL 的不同 RouterModule 配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个代码:

@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 { }

当我使用以下命令侦听路由器事件时:this.router.events.subscribe(console.log);(如果我未获得授权)我可以看到 NavigationCancel带有消息的事件:

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:

"无法加载子节点,因为路由的守卫"path: ''"返回错误"

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

如果我获得授权 RoutesRecognized 事件会按预期触发.

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.

是否仅通过路径/网址?还是会考虑其他参数?

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

是否有其他解决方案(除了为 HomeComponent 重命名路径)?

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

推荐答案

路由器只是将 url 与配置的路由的 path 参数进行比较.

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

它采用与 url 开头匹配的第一个根路由,然后使用 url 的其余部分(path 的 url)继续匹配根路由的子路由匹配的根路由在开始时被删除).这一直持续到剩余的 URL 为空并且不存在带有 path: ''(空路径)的子路由.

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.

一种方法是重新配置路由器 (resetConfig()),例如当 AuthGuard 返回 true 时.

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

这篇关于相同 URL 的不同 RouterModule 配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆