我有以下功能:
const role: string = tokenPayload.params.role.map(r => {
return r.value;
}) [0];它返回以下结果:
author
如果我删除索引[0],它将返回以下内容:
["author", "admin"]
函数是否有可能以与第一个示例相同的格式返回所有值?
常量“角色”将在只接受特定格式结果比较===中使用。为了更好地理解,我将使用完整的函数:
canActivateChild(route: ActivatedRouteSnapshot): boolean {
const helper = new JwtHelperService();
const expectedRole = route.data.expectedRole;
const token = this.authService.getToken();
const tokenPayload = helper.decodeToken(token);
const role: string = tokenPayload.params.role.map(r => {
return r.value;
}) [0];
console.log(role);
if (!this.authService.isAuthenticated() || role !== expectedRole) {
this.router.navigate(['/admin']);
return false;
}
return true;
}路由器组件:
{
path: 'container-users',
component: ContainerUsersComponent,
canActivateChild: [AuthGuard],
data: {
expectedRole: 'admin'
},
children: [
{ path: '', component: ListUsersComponent },
{ path: 'list-users', component: ListUsersComponent },
{ path: 'form-new-user', component: FormNewUserComponent }
]
}发布于 2018-08-21 04:41:34
您的应用程序中的用户似乎可以拥有多个角色,而您要做的是检查附加到该用户的这些角色中是否有任何角色是expectedRole。expectedRole是单个字符串值,而附加到用户的角色由某些对象的数组表示,其中角色名称存储在value属性中,因此不能使用===运算符,应使用indexOf()、some()或includes()等方法来验证用户是否分配了expectedRole。
因此,我不会使用map函数选择所有的角色名称,而是直接检查所需的角色:
const hasExpectedRole = tokenPayload.params.role.some(r => r.value === expectedRole)稍后,在if语句中
if (... || !hasExpectedRole)发布于 2018-08-21 04:33:11
使用字符串数组并检查它是否包含expectedRole字符串,而不是获取由map生成的数组的第一个元素:
roles = tokenPayload.params.role.map(r => {
return r.value;
});
// Use the following function
(roles.indexOf(expectedRole) == -1);
// Instead of this
role !== expectedRole;参见How to find if an array contains a specific string in JavaScript? -这篇文章解释了如何检查一个值数组是否包含单个值。
https://stackoverflow.com/questions/51937645
复制相似问题