问题描述
我需要检查后端的身份验证状态,但是在可观察到的返回完成之前,代码已完成.这将导致未定义.
I need to check te back-end for authentication status, however te code completes before te observable return is finished. Which would result in an undifined.
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
this.isAuthenticated();
return this.authenticated;
}
isAuthenticated(){
this.loginService.isAuthenticated()
.subscribe(status => this.authenticated = status)
}
我将如何更改此代码,以便在代码返回之前,等待可观察对象完成以获取身份验证状态.
How would i change this code so i wait for the observable to complete to get the authenticated status before the code returns.
注意:Angular canActivate方法不允许我编写如下所示的代码:
Note: the Angular canActivate method does not allow me to write the code as shown below:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
this.loginService.isAuthenticated()
.subscribe(status => {
this.authenticated = status;
return this.authenticated;
});
}
这将导致以下错误:
针对此错误的解决方案的建议也将有所帮助.
A suggestion for a solution for this error would also be helpful.
推荐答案
使用async/await and promise解决了该问题
Solved the issue with async / await and promise
LoginService首先导入到Promise:
The LoginService first import toPromise:
import 'rxjs/add/operator/toPromise';
然后在LoginService中创建一个异步方法
Then created an async method in the LoginService
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+等待方法/可观察完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!