Angular 角度2+;等待方法/可观察项完成

Angular 角度2+;等待方法/可观察项完成,angular,Angular,我需要检查te后端的身份验证状态,但是te代码在te可观察返回完成之前完成。这将导致未经罚款的罚款 canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { this.isAuthenticated(); return this.authenticated; } isAuthenticated(){ this.loginService.isAuthenticated

我需要检查te后端的身份验证状态,但是te代码在te可观察返回完成之前完成。这将导致未经罚款的罚款

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    this.isAuthenticated();        
    return this.authenticated; 
}

isAuthenticated(){
    this.loginService.isAuthenticated()
        .subscribe(status => this.authenticated = status)
} 
我将如何更改此代码,以便在代码返回之前等待observable完成以获得已验证的状态

注意:Angular canActivate方法不允许我编写如下所示的代码:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    this.loginService.isAuthenticated()
        .subscribe(status => {
            this.authenticated = status;
            return this.authenticated;
        });
}
这将导致以下错误:

类“AuthGuard”不正确地实现了接口“CanActivate”。
属性“canActivate”的类型不兼容。 类型'(路由:ActivatedRouteSnapshot,状态:RouterStateSnapshot)=>void'不可分配给类型'(路由:ActivatedRouteSnapshot,状态:RouterStateSnapshot)=>boolean | Observable | Pr。 类型“void”不可分配给类型“boolean | Observable | Promise”


对于此错误的解决方案的建议也会很有帮助。

您可以将可观测值返回为
可观测值


使用async/Wait和promise解决了这个问题

LoginService首次导入Promise:

import 'rxjs/add/operator/toPromise';
然后在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 } });    
}

canActivate应该返回true或false,而不是可观察的,这是可能的吗?而且,如果订阅,后端总是返回;对或错。我应该添加Subscribe()方法吗?@phicon这正是您的错误消息所说的,
boolean | Observable | Promise
。它应该返回布尔值、布尔值的可观测值或布尔值的承诺
this.authenticated
在您的原始代码中未定义。我在尝试实现自定义auth-guard时遇到了完全相同的问题,该自定义auth-guard使用不同的角色授权/不登录用户。你救了我一天。
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 } });    
}