Angular 5多个条件路由:"AuthGuards" [英] Angular 5 multiple Conditional Routing : "AuthGuards"
问题描述
我正在尝试在angular 5中创建条件路由,并且我已经看到了这篇文章以及angular的官方里程碑页面: Angular2条件路由.
i am trying to create conditional routing in angular 5 and i have seen this post and the official milestone page of angular: Angular2 conditional routing.
但是我没有找到一种基于输入变量创建多个条件的方法.这是我的代码:
But i didn't find a way to create multiple conditions based on input variables. here is my code :
import { Injectable } from '@angular/core';
import {CanActivate, Router, RouterStateSnapshot, ActivatedRouteSnapshot} from '@angular/router';
import {AuthServiceService} from './auth-service.service';
@Injectable()
export class AuthguardService implements CanActivate{
constructor(
private router: Router,
private AuthService:AuthServiceService
) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
if(this.AuthService.ValidAs("User")!=true){
this.router.navigate(['pages/login']);
return false;
}else{
return true;
}
}
}
我的 AuthService.ValidAs()
方法采用一个参数来确定要尝试并验证为合法访问用户的用户类型,并返回一个布尔值.我有三种类型的用户,如何将额外的参数传递给路由中的 canActivate
属性,以将其用作我的 ValidAs
方法的参数.
My AuthService.ValidAs()
method takes an argument to determine the type of user to try and validate as rightful to access a route and returns a boolean. i have three types of users, how do i pass extra arguments to the canActivate
property in my routes in order to use that as argument to my ValidAs
method.
如果还有其他方法可以创建多个 canActivate
实例而无需复制文件,请告诉我.
If there is any other way to create multiple canActivate
instances without multiplying files, let me know.
推荐答案
您可以将 data
对象传递给任何这样的路由:
You can pass a data
object to any route like that:
...
{
path:'dashboard',
component:DashboardComponent,
canActivate:[
AuthGuard
],
data:{
roles: ['ROLE_ADMIN', 'ROLE_EDITOR', 'OTHER_ROLE'],
// any other relevant data to make your checks
}
},
...
然后在AuthGuard中,您可以检索以下数据:
Then in your AuthGuard you can retrieve the data like:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
...
const roles = route.data[ 'roles' ] as Array<string>;
// Do other checks here
...
}
这篇关于Angular 5多个条件路由:"AuthGuards"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!