Automatic Loader With Ajax Call on Angular
I continue with Angular and today I will introduce how to display a loader when you do an ajax request. The classic method is everytime you make your request you display your loader then when you receive the answer you hide/destroy it. Well this is good but do this everytime is really boring and if you change your loader and you have to update the code to display/hide it it start to be horrible…
Hopefully with frameworks like Angular you can intercept your request before sending it and after receiving the response (like a before_action and after_action in Rails).
Everything happen with the object httpProvider and with two arrays
transformRequest is an array which store some functions to process the params before sending them. In our case we will not use it to manage the parameters but only to have a function called before each requests.
responseInterceptors is another array with a list of functions to call when the response from the server is just arrive.
Now we know a bit more about those functions, let’s start to code it
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
I will not talk about the first functions, I think it’s clear enough I just use the class active to show/hide the loader, like that you can do some awesome css3 effect ;).
The thing to be aware is in the responseInterceptors array, functions in this array don’t do anything except returning a function and we have to take car of what we return because Angular check the responses of those functions. When you are aware of this you can just start or stop your loader simply.