Delay the route canActivate method call till backend service return result in angular 7

634 Views Asked by At

Need to delay the route canActivate method call until my Authentication service return user role for the user id.

Our angular application doesn't have any login page, it uses user id from the server login. When user access the URL, authentication service get called in app.compoment.ts but before the service return any result, canActivate method get called, and doesn't have the user role at that time. So blocks all user access.

I have tried using async and wait with https call to get the user data, but that also not worked. Can anyone help here?

1

There are 1 best solutions below

1
On

Here, pipe() of rxJS is useful, rather subscribe first use pipe().

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean>  {
    return this​.​loginService​.​isLoggedIn​().​pipe​(
        map(e => {
           if (e) {
               return true;
             } else {

             }
         }),
          catchError((err) => {
             this​.​router​.​navigate​([​'/login'​]);
             return of(false);
           })
      );
  }