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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With