angularguard

Angular AUTH Guard not working when waiting for API response


I am using AUTH Guard in my angular application. It is working properly. But when I am waiting for API response, The referenced page does not load. My API is working properly. Is there any timeout issue in AUTH guard or some other problem? Please help.

in my memberDetails-routing.module:

 const routes: Routes = [
        {
            path: '', component: MemberLayoutComponent,
            children: [
                { path: 'members', component: MemberListComponent , data: { roles: ["SuperAdmin"] }, canActivate:UserAuthGuard] }]
        }];

in my member-auth.guard.ts:

canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    
   return true; // Here it is working properly and members page is loaded
   
   this.apiService.getMemberSettings().subscribe((response: any) => {
       return true; // Here API is returning response but members page is not loaded

   }
}

Solution

  • canActivate will not wait for subscribe response. just return

    canActivate(
        route: ActivatedRouteSnapshot,
        state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
        return this.apiService.getMemberSettings();
       }
    }
    
    

    in canActivate you should return Observable/Boolean/Promise

    Docs: https://angular.io/api/router/CanActivate