返回布尔值而不是订阅canActivate

时间:2017-04-19 19:59:44

标签: angular rxjs angular2-routing

我有一个受canActivate防护保护的组件。 checkLogin函数中的Authguard从一个observable订阅,但我不知道如何从它返回一个布尔值到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并且用户应该能够登陆被保护的路线但是如果它是假的,他应该被导航到error-user

Angular2 - return boolean with subscribe to canActivate这个问题与我的问题类似,但无法解决我的问题。

有人可以帮忙吗。

1 个答案:

答案 0 :(得分:8)

canActivate也可以返回一个observable,请参阅定义CanActivate-interface。只需相应更改您的退货类型。

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;
        }
    });
  }
相关问题