Angular 2+等待方法/ observable完成

phi*_*con 22 angular

我需要检查te后端的身份验证状态,但te代码在完成可观察的返回之前完成.这将导致一个unifined.

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

isAuthenticated(){
    this.loginService.isAuthenticated()
        .subscribe(status => this.authenticated = status)
} 
Run Code Online (Sandbox Code Playgroud)

我将如何更改此代码,以便我等待observable完成以在代码返回之前获得经过身份验证的状态.

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

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    this.loginService.isAuthenticated()
        .subscribe(status => {
            this.authenticated = status;
            return this.authenticated;
        });
}
Run Code Online (Sandbox Code Playgroud)

这导致以下错误:

类'AuthGuard'错误地实现了接口'CanActivate'.
属性'canActivate'的类型是不兼容的.类型'(路由:ActivatedRouteSnapshot,state:RouterStateSnapshot)=> void'不能分配给类型'(route:ActivatedRouteSnapshot,state:RouterStateSnapshot)=> boolean | 可观察的| 公关......".类型'void'不能赋值为'boolean | 可观察的| 诺言'.

对此错误的解决方案的建议也会有所帮助.

phi*_*con 19

解决了async/await和promise的问题

LoginService首先导入toPromise:

import 'rxjs/add/operator/toPromise';
Run Code Online (Sandbox Code Playgroud)

然后在LoginService中创建了一个异步方法

  async isAuthenticated(){
     const response = await this.http.get('/login/authenticated').toPromise();
     return response.json();
  }
Run Code Online (Sandbox Code Playgroud)

然后在组件中:

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 } });    
}
Run Code Online (Sandbox Code Playgroud)


eko*_*eko 6

你可以将observable作为 Observable<boolean>

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    return this.loginService.isAuthenticated()
        .map(status => {
            console.log(status);
            this.authenticated = status;
            return true;
        }).catch((err) => {
            console.log(err);
            return Observable.of(false);
        });
}
Run Code Online (Sandbox Code Playgroud)