Create Angular Resolvers to retrieve the product data from the Service

InstructorBram Borggreve

Share this video with your friends

Send Tweet

In our 'container components' we use the ngOnInit lifecycle hook to subscribe to our service. While this works, there is a downside: the components get loaded before the data is available, which results in that we show empty components. This is particularly visible on slow connections.

To fix this we create a ProductsResolver, and implement the resolve method that fetches the data from the service. In ProductRoutingModule we add the resolve property to our route, and add make the ProductsResolver resolve and store the data in the products property.

Inside our ngOnInit in ProductListComponent we can now subscribe to the route data, which makes the usage of the service in this component obsolete.

We do the same for the ProductDetailComponent. After this there are no longer empty components, the router will not navigate after the data is retrieved.