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

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

问题描述

我有一个受canActivate保护的组件. checkLogin函数中的Authguard从可观察的对象进行订阅,但是我不知道如何从中将布尔值返回到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为true,则它应该只返回true,并且用户应该能够在受保护的路线上着陆,但是如果为false,则应该导航至error-user.

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也可以返回一个可观察的对象,请参见定义

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天全站免登陆