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;
}
So what is Angular Resolver? Angular Route Resolver is used for pre-fetching some of the data when the user is navigating from one route to another. It can be defined as a smooth approach for enhancing user experience by loading data before the user navigates to a particular component.
To test the resolver we need to render RouterOutlet . const fixture = MockRender(RouterOutlet); Additionally, we also need to properly customize mocked services if the resolver is using them to fetch data. const dataService = TestBed.
Generate an application with routing enabledlink The following command uses the Angular CLI to generate a basic Angular application with an application routing module, called AppRoutingModule , which is an NgModule where you can configure your routes.
Resolve guard is used in the scenario when we want to ensure whether there is data available or not before navigating to any route. If there is no data then it has no meaning to navigate there. It means we have to resolve data before navigating to that route. Here comes the role of Angular Resolve guard.
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
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