use angular resolvers to avoid data subscribe chaos


Developers of Angular applications usually get their data from APIs, using HTTP. Most of the time that data is acquired asynchonously. Whilst the asynchronous programming model has some well documented advantages, such as the client being able to show most of the view even whilst slow running queries are still running in the background, it also adds some complications.

For example, if the Angular App contains client side calculations that use reference data as inputs, the reference data must obviously be there before the client side calculations can be made.

In Angular, data is usually returned from a service using an Observable which is subscribed to early in the component lifecycle. When the data arrives the component can use it.

So within a component if X = A + B, and A and B are pieces of data that come from different API endpoints, the component can't just subscribe to A to calculate X since the endpoint that delivers B might not have returned any data yet. Also, since each endpoint may be returning data from a completely different source system it isn't clear which piece of data will be returned first as the running times for the server side queries may vary wildly. 

This is the use case that Angular resolvers were created for. Resolvers ensure that the data required by a component is already there before the component is loaded. This means that users don't have to write any complicated logic within a component to handle the vagaries of when data from various services arrive, instead Angular handles all that and only loads the component when all the data required is present.  

Implementing resolvers is straightforward and is described very well here: https://angular.io/api/router/Resolve

Latest posts