I'm a newbee in Angular 2+ . Some people use Resolver between http service getting data and a component.
export class UserResolver implements Resolve<User> {
constructor(
private service: UserService,
private router: Router
) {}
resolve(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<User> {
const id = route.paramMap.get('id');
return this.service.getUser(+id)
.catch(err => {
console.error(err); // deal with API error (eg not found)
this.router.navigate(['/']); // could redirect to error page
return Observable.empty<User>();
});
}
}
Questions are:
Take a look at this introduction to Angular Resolvers. Looking at the steps below, notice that in step 2 your example is returning an Observable.
Quoting from the article:
So basically resolver is that intermediate code, which can be executed when a link has been clicked and before a component is loaded.
... here is the high level approach:
General Routing Flow
Routing Flow with Resolver
Steps 2,3 and 4 are done with a code called Resolver.
Thanks to Jim Cooper Pluralsight course: https://app.pluralsight.com/player?course=angular-fundamentals&author=jim-cooper&name=angular-fundamentals-m5&clip=8&mode=live
In case of first approach without Resolver we need to wait until data is loaded via asyncronous subscribe. In component some elements are displayed immediately and some after Observable.subscribe call.
In second case resolver catches all data and passed it to the component Data in component is not shown up until all component is loaded.
So resolver helps to cook data before component is shown.
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