我有Auth防护,它基于本地存储值(如果存在或不存在)。但是发生了什么canActivate()函数在从本地存储获取值之前返回null值。我该怎么做才能实现这个机制?
我的代码
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
this.check = this.usr.getUserLoggedIn().subscribe((data) => {
// this.check = data;
console.log(data);
});
// console.log('check', this.check);
if (this.check === true) {
return true;
} else {
// alert('else');
this.router.navigate(['/authentication/login']);
return false;
}
}
服务功能代码:
getUserLoggedIn() {
return this.localStorage.getItem('isUserLoggedIn');
// return this.isUserLoggedIn;
}
答案 0 :(得分:0)
您可以尝试此解决方案
服务功能代码:
getUserLoggedIn() {
return localStorage.getItem('isUserLoggedIn');
// return this.isUserLoggedIn;
}
setUserLoggedIn(data) {
localStorage.setItem('isUserLoggedIn',data);
}
ts文件代码:
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
this.check = this.usr.getUserLoggedIn();
// console.log('check', this.check);
if (this.check) {
return true;
} else {
// alert('else');
this.router.navigate(['/authentication/login']);
return false;
}
}