返回布尔值而不是订阅canActivate

Aak*_*kur 5 rxjs angular2-routing angular

我有一个受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
Run Code Online (Sandbox Code Playgroud)

所以我想要的是如果它this.checkService是真的它应该返回true并且用户应该能够登陆被保护的路线但是如果它是假的,他应该被导航到error-user.

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

有人可以在这帮忙.

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