Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is benefit in resolvers angular 5

Tags:

angular

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:

  1. What is practical benefit of that? (i see only redundant class as a bridge on each invocation)
    1. Is this recommended way and if should refactor existing code.
like image 416
Lapenkov Vladimir Avatar asked Dec 10 '22 06:12

Lapenkov Vladimir


2 Answers

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

  1. User clicks the link.
  2. Angular loads the respective component.

Routing Flow with Resolver

  1. User clicks the link.
  2. Angular executes certain code and returns a value or observable.
  3. You can collect the returned value or observable in constructor or in ngOnInit, in class of your component which is about to load.
  4. Use the collected the data for your purpose.
  5. Now you can load your component.

Steps 2,3 and 4 are done with a code called Resolver.

like image 200
Todd Palmer Avatar answered Dec 12 '22 18:12

Todd Palmer


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

  1. 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.

  2. 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.

like image 22
Lapenkov Vladimir Avatar answered Dec 12 '22 18:12

Lapenkov Vladimir