Mastering Web Application

(Rick Simeone) #1
Chapter 7
if ( response.headers()['content-type'] == "text/plain") {
response.data = $sanitize(response.data);
};
return response;
});
}

This interceptor checks the response object's content-type. If it is text/plain, we
sanitize the response object's data, and then return the response promise object.


Creating a securityInterceptor service


We will create a securityInterceptor service that will work with the response
promise object from the server. In our interceptor, we check to see if the response
promise object is rejected with a 401 authorization error. In that case, we can create
a new promise for a retry of the original request, and then return that to the caller,
instead of the original.


The original idea for this came from an excellent blog post
by Witold Szczerba: http://www.espeo.pl/2012/02/26/
authentication-in-angularjs-application.

We create the securityInterceptor as a service, and then add it to the $http
service responseInterceptors array.


.config(['$httpProvider', function($httpProvider) {
$httpProvider.responseInterceptors.push(
'securityInterceptor');
}]);

We have to add the securityInterceptor service by name,
rather than the object itself, because it depends upon services that
are not available in the config block.

For our securityInterceptor service we implement the interceptor as a service, so
that we can have other services injected into it.


We can't inject $http directly into our interceptor, because it
would create a circular dependency. Instead, we inject $injector
service, and then use it to access the $http service at call time.

.factory('securityInterceptor',
['$injector', 'securityRetryQueue',
Free download pdf