Angular 2+等待方法/可观察完成

标签 angular

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

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/

相关文章:

angular - 全局安装 angular-cli 后无法识别 ng 命令

Angular CLI 7 Webpack Bundle Analyzer 模块串联

angular - 错误 TS2300 : Duplicate identifier 'PropertyKey' in node_modules/@types/core-js/index. d.ts

angular - 尽管 X-XSRF-Token header 已正确发送,但仍收到 Laravel CSRF token 不匹配错误

javascript - 将字符串转换为 Angular 中的函数调用

angular - 延迟加载模块中的 Angular 组件是否获取全局服务的副本?

Angular 2在路由时传递对象

angular - 如何强制开发人员使用方括号而不是大括号?

Angular 12 - 双向绑定(bind)给出错误 : The property and event halves of the two-way binding 'prop_name' are not bound to the same target

javascript - 错误 : Could not find source map for in Angular2, Karma、Webpack 和 Istanbul 尔