AngularJS, code.explode, Coding

Using Response Interceptors to Show and Hide a Loading Widget: Redux

In my previous post Using Response Interceptors to Show and Hide a Loading Widget I showed how to display a loading widget whenever an Ajax request started and hide it when all the requests completed by using a $http resource interceptor.

Unfortunately, I violated one of the core tenets of AngularJS’ best practices by modifying the DOM outside of a directive. I want to thank everyone who brought that to my attention and provided examples on how to clean up the code.

This post will walk through the revised code to show how to do it properly. I will also provide a second solution, that I think is even better structured, that uses a Publish/Subscribe pattern to encapsulate the whole messaging solution and keep the publishers and subscribers from having to know anything about the notification mechanism.

Continue reading

Standard
AngularJS, code.explode, Coding

Mocking Promises in Unit Tests

If you’ve spent some time writing services in AngularJS that front-end Web APIs, you have probably used the $http service. One of the prevalent code patterns that tends to develop involves calling the .then() method on the promise that is returned from the various $http methods. This in effect waits to execute code until the asynchronous request returns and the promise is resolved.

The more complicated the Web API you are interacting with, the more your controller code tends to end up with several bits of code as shown below:

    user.requestCurrentUser().then(function() {
        $scope.currentUser = user.getCurrentUser();
    });

Testing this code can be a bit problemsome for newcomers to AngularJS. This article shows a simple way to mock your services to provide similar functionality so you can unit test your controllers that contain these type of code patterns.

Continue reading

Standard