1

Why would one return an Observable from a resolver in Angular? How is this different than simply subscribing to a method in a service/store in the component itself? I thought a resolver's purpose is to ensure the data is present before the component loads.

cyberguy
  • 233
  • 3
  • 10

1 Answers1

2

From Angular.IO's documentation about Resolve:

Resolve

Interface that classes can implement to be a data provider. A data provider class can be used with the router to resolve data during navigation. The interface defines a resolve() method that will be invoked when the navigation starts. The router will then wait for the data to be resolved before the route is finally activated.

It's different than simply subscribeing to a method in a service/store in the component itself because in that case, the route that loads up the Component would already be activated and the API call would be made after that. So the user would probably have to wait for the data to load up.

Now, in most of the cases you'd not require Resolve in the first place. It's only a matter of how fast your API responds and whether there's a significant delay in fetching the data that might hamper the UX.

SiddAjmera
  • 38,129
  • 5
  • 72
  • 110
  • So, if I return an Observable from the resolver and subscribe in the component, this subscribing happens before the component loads? Versus subscribing to a service instead, the component may be loading at the same time the subscription is taking place? – cyberguy Jan 03 '20 at 01:29
  • You don't really `subscribe` to the `Observable` that you return in the `resolver`. You have access to the data it is wrapping in the activated component via `ActivatedRoute`'s `snapshot.data` property. And yeah, if you're `subscribe`ing to the `Observable` from the service inside the Component, the Component will be loading(or at-least it's `ngOnInit` would be have been called by the time considering that you made the Service call inside `ngOnInit`) and the subscription would take place in parallel. – SiddAjmera Jan 03 '20 at 01:47