GameCoder007
GameCoder007

Reputation: 73

Angular resolver not waiting for api results

I am using Angular 11.0.5. On every reload I need to call one api (like permission) and then I need to redirect to the specified route. For this I am using Angular Resolver. And I added this resolver in the main route. Attaching the code.

AuthResolver

@Injectable({ providedIn: 'root' })
export class AuthResolver implements Resolve<any> {
  constructor(
    private _Router: Router,
    private _PermissionService: PermissionService
  ) { }

  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<any> | Promise<any> {
    if (!AppUtils.isLoggedIn()) {
      return this._Router.navigate(['app/auth/logout'])
    } else {
      // setPermissions returns Observable
      return this._PermissionService.setPermissions();
    }
  }
}

main-routing.module.ts

{
    path: '', component: MainLayoutComponent,
    resolve: {
      auth: AuthResolver
    },
    children: [
    ...
    ]
}

This code triggering the api call on every reload. but it was not waiting for the api result to re-direct to the route. I need angular route only when api result is success. Is there is any way to wait the route until api returns the response.

Thanks in advance!

Upvotes: 0

Views: 2240

Answers (1)

H3AR7B3A7
H3AR7B3A7

Reputation: 5261

Your Resolver Not Returning Data

Your resolve function in the Resolver is supposed to return the data. Currently you don't seem to be calling any data endpoint. You are either routing or setting some permissions. (Are you confusing a Resolver with a Guard?)

Example of a Resolver

Resolver:

resolve(
  route: ActivatedRouteSnapshot,
  state: RouterStateSnapshot
): DataResolved | Observable<DataResolved> | Promise<DataResolved> {
  return this.dataService.getData()
  .pipe(
    map(data => ({ data })),
    catchError(error => {
      const message = `Retrieval error: ${error}`
      console.error(message)
      return of({ data: [], error: message } as DataResolved)
    })
  )
}

Your route:

{
  path: '',
  component: SomeComponent,
  resolve: { resolvedData: DataResolverService },
},

Getting the data from the route in your component:

ngOnInit() {
  this.data = this.route.snapshot.data['resolvedData'].data;
}

You can also subscribe to the data object of the route, which in some cases might be necessary.

Here's the full example including error handling in a Stackblitz.

Upvotes: 1

Related Questions