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

查看:76
本文介绍了相同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:"的后卫返回false".

"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.

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

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

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

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