我正在寻找检查angular中组件的管理员角色的最佳方法。
我在组件中有以下代码
checkIfIsAdmin(): any {
let user_string = localStorage.getItem("currentUser");
if (!isNullOrUndefined([user_string])) {
console.log(user_string);
return true;
} else {
return null;
}
}
我需要使用以下格式检查收到的ROLE_ADMIN
:
{
"longId": 4,
"name": "bbb",
"email": "bbb@gmail.com",
"userName": "bbb",
"token": "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiI0IiwiaWF0IjoxNTU5NDk0NTczLCJleHAiOjE1NTk0OTQ4NzN9.XmSHywZv09b4BR9-NxyCTVPF33pLsk3QtTEXQMQF4YHW7i27Ghj2Uh3WZAegpG4rdSImKcm1wMgJsPLpHcTyew",
"roles": [
"ROLE_USER",
"ROLE_ADMIN"
]
}
我不知道如何在if
条件下迭代角色,有人可以帮助我吗?
答案 0 :(得分:0)
根据您的代码,我假设-
user_string = {"longId":4,"name":"bbb","email":"bbb@gmail.com","userName":"bbb","token":"eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiI0IiwiaWF0IjoxNTU5NDk0NTczLCJleHAiOjE1NTk0OTQ4NzN9.XmSHywZv09b4BR9-NxyCTVPF33pLsk3QtTEXQMQF4YHW7i27Ghj2Uh3WZAegpG4rdSImKcm1wMgJsPLpHcTyew","roles":["ROLE_USER","ROLE_ADMIN"]}
如果我的理解正确,请执行以下操作-
checkIfIsAdmin(): any {
let user_string = localStorage.getItem("currentUser");
const user = JSON.parse(user_string);
if (user ["roles"]) {
const roles = user["roles"];
const index = roles.indexOf("ROLE_ADMIN");
return index >= 0;
} else {
return false;
}
}
答案 1 :(得分:0)
您可以使用JSON.parse(user_string)
将此字符串转换为对象。
例如:
const userData = JSON.parse(user_string);
return userData["roles"].indexOf("ROLE_ADMIN") !== -1;
答案 2 :(得分:0)
尝试一下:
checkIfIsAdmin(): any {
let user_string = localStorage.getItem("currentUser");
return !!user_string && user_string.roles.includes('ROLE_ADMIN')
}
//user_string is undefined result=false
//user_string contains "ROLE_ADMIN result = true
//user_string does not contain "ROLE_ADMIN" result =false