Angular 2 : Sending requests with cache control headers

Sometimes we need to send post requests to server with cache control so that the browser does not cache the response for subsequent request.

This could lead to pretty frustrating situations with some browsers(that’s you, IE!) having strict cache control and we will see in a minute how we will wrap around the Angular’s HTTP service to tell the browser to not cache the requests.

So, in short, what we need to do is to wrap both GET and POST requests so that they are perceived as a unique every time those requests are made. It’s simple for GET requests. We just need to create a random string and attach it with GET request URL:

For the POST requests, we generate special cache control headers like so:

That’s it!

 

alexey

alexey

Application developer, movie buff, occasional reader and a huge Manchester United fan.
alexey
  • Fran Serrano

    Hi Alexey,

    Just to mention that, since Angular 4.3, with the new “commons/http” module, you need to assign the “appended” header result to the headers object. Otherwise, the updates are not reflected in the headers object that you apply i.e:

    headersAdditional = headersAdditional.append(‘Cache-control’, ‘no-cache’);

    Thanks for the article in any case :O)
    Cheers
    Fran