Tom
December 18, 2020
As you will likely know, making any application with Angular, a large part of your application is requesting information from other sources whether these are your own API’s or 3rd party API’s.
When doing this, you will have periods of time where you do not have the data whilst you are waiting for the response. This is where I like to use a loading property on the state, this allows you to have a contextual loader for each state, so you can easily present to the user some form of feedback that your application is working for each different part of the application (the states).
For example, I might have a user invoices state and a user payment methods state, responsible for getting two different pieces of information regarding the user. So let’s say you go to the users billing page, this will dispatch events to get that information about our user.
In my states, when the action gets called, I immediately patch the state to set the loading property to true, so this feedback that the application is working can be shown to the user.
Invoice-state.ts
invoice-component.ts
invoice-component.html
I then do the normal action to request information from the API, and once completed, I patch the state again, with all the information we requested and set the loader to false. So for the user, the loader can disappear, and the content can be rendered.
Here is a basic example, and how it will look, you can then add any snazzy loaders or messages you like:
Sometimes you may have two different actions on the same state that retrieve similar, but different data and you won’t want to show any content until both parts have loaded and stored in the state. For example, you may want to load the list of a user's invoices and also load their latest invoice to show at the top of the page. You would keep these in the same state but you can not set the loading as false once one has loaded, as the other may not have completed yet.
In these instances, I like to use a string, boolean Map to store the state of each loading function on the state, this way I can show individual loaders for each function, or show a universal loader for anything regarding that state if there are records in the Map.
That’s how I handle loading in my Angular applications, in bigger applications you could even break this out into it’s one loading state that makes use of the Map and other states can update it when they perform actions.
A Web, Tech, Football and Video Game enthusiast. Anything can be settled in smash! I’m a Software Engineer on the nerd.vision team with various front-end and back-end skills.