Aakash Thakur
Aakash Thakur

Reputation: 3895

return boolean instead of subscribe to 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

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 - return boolean with subscribe to canActivate this question is similar to mine but couldn't resolve my issue with it.

Can somebody help here.

Upvotes: 5

Views: 24562

Answers (2)

Vikram Sapate
Vikram Sapate

Reputation: 1297

We can return Promise too like...

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Promise<boolean> {
    return new Promise<boolean>(resolve => {
       this.service
       .function()
       .toPromise()
       .then((res) => {
         if(condition) {
            resolve(true);
         } else {
            this.router.navigate(["login"]);
            resolve(false); 
         } 
      })
      .catch(() => {
        this.router.navigate(["login"]);
        resolve(false);
       });
    });
  }

Upvotes: 1

Igor
Igor

Reputation: 62228

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;
        }
    });
  }

Upvotes: 11

Related Questions