如何允许未经授权访问其父级在Angular 4中具有AuthGuard的子路由?
我的Angular 4应用程序在文件如何允许未经授权访问其父级在Angular 4中具有AuthGuard的子路由?,angular,angular4-router,Angular,Angular4 Router,我的Angular 4应用程序在文件app.module.ts中使用延迟加载(loadChildren)设置了父路由。有些路由需要身份验证(使用canActivate),有些路由则不需要: //app.module.ts 常数路由:路由=[ //需要身份验证的路径 { 路径:“”, 儿童:[ {path:'admin',loadChildren:'./admin/admin.module#AdminModule'}, {path:'customer locator',loadChildren:'
app.module.ts
中使用延迟加载(loadChildren
)设置了父路由。有些路由需要身份验证(使用canActivate
),有些路由则不需要:
//app.module.ts
常数路由:路由=[
//需要身份验证的路径
{
路径:“”,
儿童:[
{path:'admin',loadChildren:'./admin/admin.module#AdminModule'},
{path:'customer locator',loadChildren:'。/customer locator/customer locator.module#CustomerLocatorModule'}
],
canActivate:[AuthGuard]
},
//不需要身份验证的路径
{
路径:“登录”,
组件:LoginComponent
}
];
在每个相应模块内设置子路由。例如,对于CustomerLocatorModule
中的子路由,它们已被放置在customer locator.module.ts
中:
//customer-locator.module.ts
常数路由:路由=[
{//需要身份验证
路径:“”,
组件:CustomerLocator组件
},
{//不应要求身份验证
路径:“编辑客户/:customerId”,
组件:EditCustomerComponent
}
]
由于当前已设置,路径:“”
下的所有子路由都要求访问身份验证
鉴于父路由(
customer locator
)确实需要身份验证,子路由(在本例中,指向EditCustomerComponent
)是否可能不需要身份验证?不知道这是否是最好的方法,但您可以获取已请求的路径/url并进行一些检查,有
谨防:
canActivate(route: ActivatedRouteSnapshot): Observable<any> {
//route has a snapshof of the current route
//check the route and with an if statement, return observable of(true) if the route is in your whitelist
}
canActivate(路由:ActivatedRouteSnapshot):可观察{
//路由具有当前路由的快照
//检查路由,如果路由在白名单中,则使用if语句返回observable of(true)
}
您在这里所做的只是对路线进行分组。这意味着你也可以这样做
// app.module.ts
const routes: Routes = [
// Paths that require authentication
{
path: '',
children: [
{ path: 'customer-locator', loadChildren: './customer-locator/customer-locator.module#CustomerLocatorModule' }
],
},
{
path: '',
children: [
{ path: 'admin', loadChildren: './admin/admin.module#AdminModule' },
],
canActivate: [AuthGuard]
},
// Paths that do not require authentication
{
path: 'login',
component: LoginComponent
}
];
你只是把一个小组分成两个小组。这就是你想要的吗 能否将canActivate仅移动到“admin”路径?那么它就不会保护客户定位器路径。@DeborahK问题是
客户定位器
中有一个子路径确实需要身份验证(路径:'
),而另一个子路径则不需要身份验证(路径:'edit customer/:customerId'
)。将其从顶级路径中删除,然后只将其添加到需要的路径中。如果没有激活:[AuthGuard]
,则无法使整个客户定位器路径处于活动状态,因为其某些子路由(路径:“”
)需要身份验证。问题是某些子路由(path:'edit customer/:customerId'
)不需要身份验证。然后您应该向客户定位器riuter添加防护。当父路由需要身份验证时,不可能允许某些子路由不具有身份验证。至少实现起来并不琐碎。