AngularJS Essentials
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
Dependency Injection and Services<br />
}<br />
});<br />
}<br />
var timestamp = Date.now();<br />
config.url = config.url + "?x=" + timestamp;<br />
return config;<br />
Something might happen with the request, causing an error. With the requestError<br />
interceptor, we can handle this situation. It is called when the request is rejected and<br />
can't be sent to the backend.<br />
The response interceptor is called right after the response arrives from the backend<br />
and receives a response as a parameter. It's a good opportunity to apply any<br />
preprocessing behavior that may be required.<br />
One of the most common intercepting situations is when the backend produces<br />
any kind of error, returning a status code to indicate unauthorized access, a bad<br />
request, a not found error, or even an internal server error. It could be handled by the<br />
responseError interceptor, which allows us to properly apply the correct behavior<br />
in each situation.<br />
This httpUnauthorizedInterceptor parameter, in the following code, is<br />
responsible for handling the unauthorized error and changing the login property of<br />
$rootScope, indicating that the application should open the login dialog:<br />
parking.factory('httpUnauthorizedInterceptor', function($q,<br />
$rootScope){<br />
return{<br />
'responseError' : function(rejection) {<br />
if (rejection.status === 401){<br />
$rootScope.login = true;<br />
}<br />
return $q.reject(rejection);<br />
}<br />
}<br />
});<br />
After defining the interceptors, we need to add them to $httpProvider using the<br />
config function of the Module API, as follows:<br />
config.js<br />
app.config(function ($httpProvider) {<br />
$httpProvider.interceptors.push('httpTimestampInterceptor');<br />
$httpProvider.interceptors.push('httpUnauthorizedInterceptor');<br />
});<br />
[ 86 ]<br />
www.it-ebooks.info