我需要检查后端的身份验证状态,但是代码在可观察返回完成之前完成。这将导致不确定。
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
this.isAuthenticated();
return this.authenticated;
}
isAuthenticated(){
this.loginService.isAuthenticated()
.subscribe(status => this.authenticated = status)
}
我将如何更改此代码,以便在代码返回之前等待可观察对象完成以获取经过身份验证的状态。
注意:Angular 的 canActivate 方法不允许我编写如下所示的代码:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
this.loginService.isAuthenticated()
.subscribe(status => {
this.authenticated = status;
return this.authenticated;
});
}
这会导致以下错误:
Class 'AuthGuard' incorrectly implements interface 'CanActivate'.
Types of property 'canActivate' are incompatible. Type '(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => void' is not assignable to type '(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => boolean | Observable | Pr...'. Type 'void' is not assignable to type 'boolean | Observable | Promise'.
针对此错误的解决方案的建议也会有所帮助。
最佳答案
解决了 async/await 和 promise 的问题
LoginService首先导入到Promise:
import 'rxjs/add/operator/toPromise';
然后在LoginService中创建了一个async方法
async isAuthenticated(){
const response = await this.http.get('/login/authenticated').toPromise();
return response.json();
}
然后在组件中:
async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
this.loginStatus = await this.loginService.isAuthenticated();
console.log("LOGGED IN STATUS: " + this.loginStatus);
if (this.loginStatus == true){
return true;
}
// not logged in so redirect to login page with the return url
this.router.navigate(['/layout/login'], { queryParams: { returnUrl: state.url } });
}
关于Angular 2+等待方法/可观察完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43953007/