16.07.2017 Views

AngularJS Essentials

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 4<br />

After the header configuration, the request starts to send the custom header:<br />

GET /cars HTTP/1.1<br />

Host: localhost:3412<br />

User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:29.0)<br />

Accept: application/json<br />

Accept-Language: pt-br,pt;q=0.8,en-us;q=0.5,en;q=0.3<br />

Accept-Encoding: gzip, deflate<br />

The headers can also be configured through the configuration object of each request.<br />

It will overwrite the default headers configured here.<br />

Caching<br />

To improve the performance of our application, we can turn on the framework's<br />

caching mechanism. It will store each response from the server, returning the same<br />

result every time the same request is made.<br />

However, take care. Some applications demand updated data, and the caching<br />

mechanism may introduce some undesired behavior. In the following code, we<br />

are enabling the cache mechanism:<br />

run.js<br />

parking.run(function ($http) {<br />

$http.defaults.cache = true;<br />

});<br />

Interceptors<br />

The framework also provides an incredible HTTP intercepting mechanism. It allows us<br />

to create common behaviors for different kinds of situations such as verifying whether<br />

a user is already authenticated or to gather information for auditing purposes.<br />

The first is the request interceptor. This interceptor is called before the request is<br />

being sent to the backend. It is very useful when we need to add information such<br />

as additional parameters or even headers to the request.<br />

In the following code, we create an interceptor called httpTimestampInterceptor,<br />

which adds the current time in milliseconds to each request that is made by<br />

the application:<br />

parking.factory('httpTimestampInterceptor', function(){<br />

return{<br />

'request' : function(config) {<br />

[ 85 ]<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!