返回布尔值而不是订阅 canActivate [英] return boolean instead of subscribe to canActivate

查看:34
本文介绍了返回布尔值而不是订阅 canActivate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个受 canActivate 保护的组件.checkLogin 函数中的 Authguard 从一个 observable 订阅,但我不知道如何从它返回一个布尔值到 canActivate.

I have a component protected with canActivate guard. The Authguard in the checkLogin function subscribes from an observable but I do not know how to return a boolean value from it to canActivate.

guard.service.ts

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    let url: string = state.url;

    return this.checkLogin(url);
  }

    public checkService:boolean;
  checkLogin(url: string):boolean {

         return this.loadAppSettings().subscribe(res=>{
              console.log(this.checkservice);
              if (this.checkservice == true) 
              {
                   return true; 
            }
            else{
                this.router.navigate(['/error-user']);
                return false;
            }
            });
      }//checkLogin throws error as type subscription is not assignable to type boolean

所以我想要的是,如果 this.checkService 为真,它应该只返回真,用户应该能够降落在受保护的路线上,但如果它是假的,他应该被导航到 <代码>错误用户.

So what I want is if the this.checkService is true it should just return true and the user should be able to land on the guarded route but if it is false he should be navigated to error-user.

Angular2 - 返回布尔值并订阅 canActivate 这个问题是与我的类似,但无法解决我的问题.

Angular2 - return boolean with subscribe to canActivate this question is similar to mine but couldn't resolve my issue with it.

有人可以帮忙吗.

推荐答案

canActivate 也可以返回一个 observable,见定义 CanActivate-interface.只需相应地更改您的退货类型.

canActivate can return an observable too, see the definition CanActivate-interface. Just change your return types accordingly.

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    let url: string = state.url;

    return this.checkLogin(url);
}

public checkService:boolean;
checkLogin(url: string):Observable<boolean> {
     return this.loadAppSettings().map(res=>{
          console.log(this.checkservice);
          if (this.checkservice == true) 
          {
               return true; 
        }
        else{
            this.router.navigate(['/error-user']);
            return false;
        }
    });
  }

这篇关于返回布尔值而不是订阅 canActivate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆