AngularJs Loader Bar

Loader bar is inevitable part of user experience since we cannot get ride of data transfer delay. In this post, I will try to explain my way of handling this issue on Angular Js.

I use Angular JS almost all of my web project because of various different cool feature. When I used Angular for the first time, I deal with this loader problem using HTTP Interceptor (the idea taken from probably from stack-overflow, I do not remember which post it is.). The Idea is simple, Angular let you intercept any http request and you start a loader at the beginning of each request and stop loader at the end of the request. This looked so cool and I used it. However, In the last project, I realize that I need to send couple of http request without informing the user because they do not need to see these request. So, the first method needs to be changed. I came up with following method, which is naive.

I define a service, which is nothing but a function can be called any controller. In this function, I just start my progress bar before executing request and stop after I got the response. I get f as parameter, which is actually a function. I call this function by the response I got as a result.

app.factory('loader', function() {
return {
executeGet: function(request, $scope, f) {
$scope.progressbar.start();
request.get(function(response) {
$scope.progressbar.complete();
f(response)
});
},
executePOST: function(request, data, $scope, f) {
$scope.progressbar.start();
request.save(data, function(response) {
$scope.progressbar.complete();
f(response)
});
}
};
});

This is sample Controller that shows how I call this service and use the response coming from this function.

app.controller("AppCtrl", ["$scope","$resource", "apiUrl", "loader", function($scope, $resource, apiUrl, loader) {
var SecureTextList = $resource(apiUrl + "user/secure/text/all"); // a RESTful-capable resource object
loader.executeGet(SecureTextList, $scope, function(response) {
$scope.texts = response.data.textList;
});
}]);

Of course, this is simplist version in order to show logic. You can have another function which check the response before pass it to function. For example, If you get session error from server, you can immediately redirect user to login page. Also, I seperated get and post request. There are other kinds of request types. It is possible to find more generic way of writing these method. It might be good idea to write a wrapper object which is subclass of $resource object.

I used ngProgress module by suggestion of a friend. I think It looks quite modern. It is also easy to use. Check it yourself, https://github.com/VictorBjelkholm/ngProgress