Categories
Dev JS

Let AngularJS do the heavy “Loading”

Every web application does one thing in common — Load Data. Any developer would want his user to by notified that some background loading task is running by showing a loading symbol and also might want to disable various controls on screen.

This piece of code looks fine. Show loading symbol before a http call, and hide it once the call is done. Now think of 10 such calls in one page. and 10 such different pages. There is lot of lines of repeated code. Also there could be overlaps between loading symbol codes of several calls, if not handled correctly, causing spinner to not show when needed.

So why go through all this confusion and why not leave all the handling of the loading symbol to Angular. We’ll see how exactly to do that.

$http provides a list of all the requests currently in progress. We can access this array with $http.pendingRequests. By placing a watch on the length of this array , we can decide if loading symbol is to be shown or not. This watch is ideally placed in the controller for index.html.

Once you have the above code running, you might notice that we are not able to control if we want to show/hide loading symbol only for some API calls. There might be some API calls which you’d not want to show a spinner for. We can achieve this with small modifications to the above snippet.

Here, we filter the pendingRequests array to remove any calls which do not require loading symbol to be shown. To set any http call as background, we just need to set the isBackground property of the request as true.

With this code along with loading symbols, you can also handle the enabling/disabling of elements etc. at a single place.

By Sai Kiran Kothuri

Tech enthusiast. Software Engineer at Microsoft. MS in CS Georgia tech.

Leave a Reply

%d bloggers like this: