我在 Angular 中使用 canActivate
和 guards
。我想检查用户是否经过身份验证并根据结果保护路由。
有两种类型的用户:Type1
和 Type2
,因此用户可以使用 Type1
、Type2
或未验证
。
下面的guard
是给Type1
用户的。
这是我的代码:
constructor(private authservice: AuthService, private router: Router, private route: ActivatedRoute){}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean{
const self = this;
const expectedType = "type1";
this.authservice.isUserAuthenticatedbyType(expectedType).then(
function(data){
if(data === false){
console.log(data);
self.router.navigate(['/'], {relativeTo: self.route});
}
return data;
},
function(error){
self.router.navigate(['/']);
return false;
}
);
return false;
}
问题是我进行 API 调用以验证用户是否已通过身份验证,并且 return false;
在 API 结果之前执行。所以,我暂时看到了一个不同的页面,然后它被路由到正确的页面。我该如何解决这个问题,我不想在 API 调用之前返回 false 或 true,但不这样做会产生错误。
我还尝试了以下方法:
return this.authservice.isUserAuthenticatedbyType(expectedType)
但是,如果是 unauthenticated
用户,这只会将我导航到 http://localhost:4200
url。
我有以下路线:
{ path: "", component: HomeComponent },
因此,在上面的场景中,应该调用了 HomeComponent
,但是没有调用 HomeComponent 的 ngOnInit
。
最佳答案
你也可以这样尝试:
canActivate(): Observable<boolean> | Promise<boolean> | boolean {
return new Promise(res => {
this.authservice.isUserAuthenticatedbyType("type1").subscribe(
(data) => {
if (data === true) {
res(true);
} else {
this.router.navigate(['/']);
res(false);
}
},
(error) => {
this.router.navigate(['/']);
res(false);
}
);
});
}
关于angular - 在 Angular 的 canactivate 方法中调用 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53352510/