Angular-core.js:6210错误类型错误:无法读取属性';角色';未定义的
在Angular-11中,我有以下代码:Angular-core.js:6210错误类型错误:无法读取属性';角色';未定义的,angular,Angular,在Angular-11中,我有以下代码: setRoles(roles: string | any[]){ if (roles){ // tslint:disable-next-line:prefer-const let data = [roles[0].name]; for (let i = 1; i < roles.length; i++){ data.push(roles[i].name); } localStorage.set
setRoles(roles: string | any[]){
if (roles){
// tslint:disable-next-line:prefer-const
let data = [roles[0].name];
for (let i = 1; i < roles.length; i++){
data.push(roles[i].name);
}
localStorage.setItem('roles', JSON.stringify(data));
} else {
localStorage.setItem('roles', '');
}
}
export class AuthComponent implements OnInit {
public loggedIn!: boolean;
public form = {
username : null,
password : null,
remember_me : false
};
name = null;
public error = null;
constructor(
private api: ApiService,
private token: TokenService,
private router: Router,
private auth: AuthService,
) {}
// tslint:disable-next-line:typedef
ngOnInit() {;
}
// tslint:disable-next-line:typedef
onSubmit(){
// this.notify.info("Wait...", {timeout:0});
const headers = {
'Content-Type' : 'application/json'
}
return this.api.post('auth/user/login', this.form, headers).subscribe(
data => this.tokenHandler(data),
error => this.errorHandler(error.error)
);
}
// tslint:disable-next-line:typedef
errorHandler(error: any){
// this.notify.clear();
console.log(error);
if (error.errors && error.errors.username){
this.error = error.errors.username;
}
else if (error.message === 'Unauthorized'){
this.error = null;
} else {
this.error = null;
}
}
// tslint:disable-next-line:typedef
tokenHandler(data: any){
// this.students = null;
// this.notify.clear();
console.log(data);
this.token.setRoles(data.user.roles);
this.token.set(data.token_type + ' ' + data.access_token, data);
this.auth.changeAuthStatus(true);
this.loggedIn = true;
this.router.navigateByUrl('/dashboard');
window.location.reload();
}
}
我如何解决它
谢谢您正在尝试从data.user.roles获取用户
this.token.setRoles(data.user.roles);
这不是对角色的正确引用。根据您的控制台日志,尝试下面的数据,可以看到user
被包装在results
this.token.setRoles(data.results.user.roles);
返回this.api.post('auth/user/login',this.form,headers)这里返回什么?您能告诉我们它是否进入错误块或数据吗block@Tejeshree-我如何知道返回的是什么?两个处理程序中都有控制台语句,对吗there@Tejeshree-我已使用console.log(数据)更新了代码;正在提交tokenHandler(数据:任意){
this.token.setRoles(data.results.user.roles);