Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular route resolver or onInit?

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;
}
like image 494
Nazar Kalytiuk Avatar asked Apr 03 '18 21:04

Nazar Kalytiuk


People also ask

What is an angular route resolver?

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.

How do you test angular resolvers?

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.

Which angular package is used to route to URL?

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.

What is resolve Guard in angular?

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.


1 Answers

The main difference between resolvers and onInit is the synchronicity.

  • Resolver is synchronous.

    • You should use it when you need the data before the component is loaded.
    • You block the component loading.
    • You don't inject the service into the component (you can't use other methods there)
  • OnInit is asynchronous (in your code).

    • You should use it when there is no need for the data being available before loading the component.
    • You don't block the component loading.
    • You inject the service into the component, therefore you can use other methods from this service.

Take a look at this site: https://blog.thoughtram.io/angular/2016/10/10/resolving-route-data-in-angular-2.html

like image 145
Gustavo Lopes Avatar answered Sep 18 '22 12:09

Gustavo Lopes