Answer the question
In order to leave comments, you need to log in
What are resolvers used for in Angular 2?
I was at an interview, this is what my application structure looked like:
| app-
| user.component.ts-
| users-list.component.ts
-| posts.component.ts-
| data.service.ts-
| user.resolver.ts
//The project is much larger, but this abstract structure will suffice to understand my problem.
constructor (data: data.service ... ) {
data.subscribe(... this.user = user);
data.subscribe(... this.postsOfUser = userPosts);
//Код похож на оригинал, но короче.
}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<User> {
return this.rest.getUser(route.params['id']);
}
export class UserPostsComponent {
user: User;
constructor(private router: ActivatedRoute, private rest: RestService) {
this.user = router.snapshot.data['user'];
rest.getAllPosts(router.snapshot.params['id']);
}
}
Answer the question
In order to leave comments, you need to log in
Generally speaking, you need to be careful with resolvers.
Here we first shoved everything into resolvers, and then we removed some of the non-critical content back from them, because page display was delayed for a very long time. In resolvers, you should leave only that without which you cannot show the view. Also, resolvers can be used to check access or some other things. After all, if reject gets into the resolver, the transition will not occur.
Resolve is used in cases where you need to wait for data that is transmitted to you with a delay (asynchronous). For example, in Angular 1, when a promise comes to you, you need to resolve it (translating the word/parameter often helps, njulf makes it clearer what it does), and then inject it into the controller. That is, the view waits for the data to be prepared in the route, and only then displays it.
The situation is the same in Angular 2, only Observables have appeared, in addition to Promise.
As written above. Resolve allows you to get data before the component is loaded by the route. Because Receiving data from the server can be long and so that the user does not look at the white screen, resolve is used, which receives data until the moment when routing worked for you.
It is well described here why and for what: https://bxnotes.ru/conspect/angular-5-the-complete...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question