Friday, November 14, 2014

Loading marker for Angular

With client server development you have to deal with delays when you hit the server. This is a common problem and requires a lot of boilerplate code. I will present the solution I use. It is for Angular and basically relies on the two way data binding to hook the pieces together.

Part 1 - Utility Code:
var blockLoad = ($timeout, promise, loadingFunction) => {
var markSystemLoading = $timeout(() => {
    loadingFunction(true)}, 500)
}
return promise.finally(() => {
$timeout.cancel(markSystemLoading )
loadingFunction(false);
})
}

Part 1 - Usage:
blockLoad(promise, (loading) => {
$scope.isLoading = loading;
})

This code is pretty simple aspect oriented stuff. You start a timeout since you don't want to flash loading for short waits. I have arbitrarily chosen half a second. The asynchronous promise has a finally condition that will run when it completes and mark the system as not loading. It will additionally cancel the timeout to prevent it from erroneously marking your loading condition to be true. This also returns a promise that chains with the original promise so it fits into code nicely. The usage is simple and flexible.


Part 2 - The Directive
I built this on top of a JQuery control, because I am lazy, but here is a quick directive.

function ($parse, $translate) {
    return {
        restrict: 'AC',
        link: function (scope, lElement, attrs) {
            var message = attrs.message;
            scope.$watch(attrs.hpBlockOn, function (value) {
                if (value) {
                    lElement.block({
                        message: message,
                        overlayCSS: { backgroundColor: '#CCCCCC' },
                        css: { width: '200px' }
                    });
                } else {
                    lElement.unblock();
                }                    
            });
        }
    }
}

Part 2 - Usage:
<div hp-block-on="isLoading" message="LOADING">

All this allows blocking of the UI during asynchronous requests to be added with about 4 lines. It handles errors from the requests and prevents flashing loading too soon.

No comments:

Post a Comment