What better for using resolver
service or get data in OnInit hook? For example, if I need get data from 3 different sources into 1 page better user resolver or write code into ngOnInit?
code
ngOnInit() {
service1.getData().subscribe(c => {
this.data1 = c;
});
service2.getData().subscribe(c => {
this.data2 = c;
});
service3.getData().subscribe(c => {
this.data3 = c;
});
}
OR
RouterModule.forRoot([{
path: 'page/:id',
component: blabla,
resolve: {
data1: service1,
data2: service2,
data3: service3
}
}])
ngOnInit() {
this.data1 = this.activatedRoute.snapshot.data.data1;
this.data2 = this.activatedRoute.snapshot.data.data2;
this.data3 = this.activatedRoute.snapshot.data.data3;
}
The main difference between resolvers
and onInit
is the synchronicity.
Resolver
is synchronous.
OnInit
is asynchronous (in your code).
Take a look at this site: https://blog.thoughtram.io/angular/2016/10/10/resolving-route-data-in-angular-2.html
Well it depends. If the component cannot function without the data1
, data2
, and data3
, then the resolve approach makes a lot of sense. An example would be you bank account page. You do not really care about the page until you can see the details of your account.
If you can show something to the user while he awaits for the data it might be better to get the data in the ngOnInit
. An example would be a product page, where data{1,2,3}
is a stream of recommended products. The product page can still be shown, even without the recommendations, and the recommended products can continue to load while the user can interact with the rest of the page.
It will be very hard for anyone to answer this question without a deeper understanding of your business logic requirements.
It's important to understand that route resolvers
and component ngOnInit
are two different solutions to two different problems, meaning that one tool is not better than the other.
I would say the best practice is to use both in your application, depending on the situation - sometimes it makes sense, UX-wise, to display a view synchronously (blocking until data is loaded) and other times it's better to display the view immediately and load data asynchronously.
So, it's not an application design or architectural decision - It's a UX/UI decision.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.