如何检查数组是否包含特定值?

时间:2018-08-20 19:51:28

标签: angular typescript

我具有以下功能:

const role: string = tokenPayload.params.role.map(r => {
  return r.value;
}) [0];

它返回以下结果:

author

如果我删除索引[0],它将返回以下内容:

["author", "admin"]

该函数是否可能以与第一个示例相同的格式返回所有值?

将在比较===中使用const“角色”,该比较仅接受该特定格式的结果。我将使用完整功能以更好地理解:

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 }
    ]
  }

2 个答案:

答案 0 :(得分:3)

您的应用程序中的用户似乎可以具有多个角色,并且您要尝试执行的操作是检查与用户相关联的这些角色是否为expectedRoleexpectedRole是一个字符串值,而附加到用户的角色由某些对象的数组表示,角色名称存储在value属性中,因此您不能使用===运算符,则应使用indexOf()some()includes()之类的方法来验证用户是否已分配expectedRole

因此,我将直接检查所需的角色,而不是使用map函数选择所有角色名称:

const hasExpectedRole = tokenPayload.params.role.some(r => r.value === expectedRole)

及更高版本,在if语句中

if (... || !hasExpectedRole)

答案 1 :(得分:0)

使用字符串array并检查它是否包含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?-这说明了如何检查值数组是否包含单个值。

相关问题