Перейти к маршруту, если хотя бы один охранник активен
Защитники в маршрутизации Angular2 работают в том порядке, в котором они предоставляются. Но в случае охранников с наблюдаемыми, даже если первый охранник истинен, угловой игнорирует его и применяет только результат из наблюдаемой второго охранника.
Как я могу решить это?
const mainRoutes: Routes = [
{
path: 'app',
component:MainComponent,
canActivate:[AuthGuard],
children:[
{ path: 'dashboard', component: DashboardComponent },
{ path: 'protectedRoute', component: ProtectedRouteComponent, canActivate:[Admin1Guard,Admin2Guard] }
]}
];
Первый охранник:
canActivate() :Observable<boolean>{
return this.authService.getUser().map(res=>{
if(res.user.role=="admin1")
return true;
}).take(1);
}
}
Второй охранник:
canActivate() :Observable<boolean>{
return this.authService.getUser().map(res=>{
if(res.user.role=="admin2")
return true;
}).take(1);
}
}
1 ответ
Решение
Я бы реорганизовал логику проверки ролей в один общий CheckRoleGuard
службы и прикрепите название роли для проверки к маршруту через data
имущество:
{
path: 'protectedRoute1',
component: SomeComponent,
canActivate: [CheckRoleGuard],
data: { allowedRoles: ['admin','editor'] }
},
{
path: 'protectedRoute2',
component: SomeComponent,
canActivate: [CheckRoleGuard],
data: { allowedRoles: ['admin'] }
}
А теперь для RoleGuard
оказание услуг:
@Injectable()
class CheckRoleGuard {
constructor(private authService: AuthService) { }
canActivate(route: ActivatedRouteSnapshot): Observable<boolean> {
// Retrieve the allowed roles from `route.data`.
const allowedRoles = route.data['allowedRoles'];
return this.authService.getUser()
.map(data => {
return allowedRoles.indexOf(data.user.role) !== -1;
});
}
}