angularobservablerouterguard

How can I put the router inside the observable in the guard?


I need to inject a router into my guard, but I have an Observable method returned. How can I add routing with a redirect to the login page, for example? The condition is the following: If the isAccessToLobby method returns false, then redirect to the login page.

Method:

  isAccessToLobby() {
    return this.http
      .get(
        `${environment.domain}${BackendRoutes.Authentication}`,
        this.httpOptions
      )
      .pipe(map((data: any) => data.allowAccess));
  }

Guard:

export class AuthGuard implements CanActivate {
  constructor(private router: Router, private autService: AuthService) {}
  canActivate() {
    return this.autService.isAccessToLobby();
  }
}

I tried to do this through a subscription, but if you do it inside a subscription, a subscription appears, but this is not what I need.


Solution

  • You can try with something like the following:

    export class AuthGuard implements CanActivate {
    
      constructor(private router: Router, private autService: AuthService) {}
    
      canActivate() {
    
        return this.autService.isAccessToLobby()
          .pipe(
            take(1),
            switchMap((allowAccess: boolean) =>
             !allowAccess ? 
               this.router.createUrlTree(['/example']) : 
               of(true)));
      }
    }