-1

I created the following AuthenticatedGuard in Angular 9:

export class AuthenticatedGuard implements CanActivate {

  constructor(private authenticationService: AuthenticationService) { }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

      return this.authenticationService.isSignedIn();

      this.authenticationService.signInRedirect({ state: { url: state.url }}).subscribe();

  }

}

The method authenticationService.isSignedIn returns an Observable<boolean> and authenticationService.signInRedirect() returns an Observable<any>.

The behaviour should be:

If authenticationService.isSignedIn is false then do:

this.authenticationService.signInRedirect({ state: { url: state.url }}).subscribe();

Can this be done and still use Observable?

Miguel Moura
  • 28,129
  • 59
  • 187
  • 356
  • By returning you exit the function instantly is that what you want? the second line will never run. – Get Off My Lawn Jun 19 '20 at 21:21
  • I could subscribe this.authenticationService.isSignedIn() and check if its value is true or false. If true I would return true, if false I would call signInRedirect. My question is: does this make sense? Should I try to return Observable of Boolean instead of Boolean? But if I do not evaluate the value of authenticationService.isSignedIn then how can I redirect? – Miguel Moura Jun 19 '20 at 21:25

2 Answers2

1

Change guard to :-

export class AuthenticatedGuard implements CanActivate {

  constructor(private authenticationService: AuthenticationService) { }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

      return this.authenticationService.isSignedIn().pipe(tap((res)=> {
            if(!res) {
              this.authenticationService.signInRedirect({ state: { url: state.url }}).subscribe();
            }
      }));;

  }

}
Aakash Garg
  • 8,402
  • 2
  • 5
  • 19
1

You can await the isSignedIn() call and then do your signInRedirect() to redirect like this, we also need to return a true/false value.

async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
  const isSignedIn = awiat this.authenticationService.isSignedIn().first().toPromise();
  if (!isSignedIn) {
    this.authenticationService.signInRedirect({ state: { url: state.url }}).subscribe();
    return false;
  }
  return true;
}
Get Off My Lawn
  • 27,770
  • 29
  • 134
  • 260