Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get async data with Angular resolver

Tags:

angular

rxjs

I have resolver in my Angular 8 app

export class UserResolver implements Resolve<any> {

  constructor(
    private authService: AuthService,
  ) { }

  resolve() {
    this.authService.user.subscribe(user => {
      return user
    })
  }
}

But this is assign null to a router data, because user came with async function in my service (it came from the Subject). How can I make resolver to wait for data from my service to be returned, and not assign null value to a data?

like image 575
Vladimir Humeniuk Avatar asked Jun 27 '26 20:06

Vladimir Humeniuk


1 Answers

Two things:

1) Remove the subscribe and let the resolver handle the subscription.

2) Return the Observable, not the data.

Something like this:

export class UserResolver implements Resolve<any> {

  constructor(
    private authService: AuthService,
  ) { }

  resolve() {
    return this.authService.user;
  }
}

UPDATE:

Mine works, waiting and then returning the data. Mine looks like this:

constructor(private productService: ProductService) { }

    resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<IProduct> {
        const id = +route.paramMap.get('id');
        return this.productService.getProduct(id);
    }

Notice that there is no subscribe and I'm returning the Observable returned from the http get operation.

My route configuration looks like this:

@NgModule({
  imports: [
    SharedModule,
    InMemoryWebApiModule.forRoot(ProductData),
    RouterModule.forChild([
      { path: 'products', component: ProductListComponent },
      {
        path: 'products/:id',
        component: ProductDetailComponent,
        resolve: { resolvedData: ProductResolver }
      },
      {
        path: 'products/:id/edit',
        component: ProductEditComponent,
        resolve: { resolvedData: ProductResolver }
      }
    ])

If you want working code, I have a more complex version of the above (more complex due to added exception handling) here: https://github.com/DeborahK/Angular-Routing/tree/master/APM-Final

like image 175
DeborahK Avatar answered Jun 30 '26 09:06

DeborahK