Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent IE11 caching GET call in Angular 2

I have a rest endpoint that returns a list on a GET call. I also have a POST endpoint to add new items and a DELETE to remove them. This works in Firefox and Chrome, and the POST and DELETE work in IE11. However, the GET in IE11 only works on initial load of the page. Refreshing returns cached data. I have seen post about this behavior in Angular 1 but nothing for Angular 2(release candidate 1).

like image 798
cmaynard Avatar asked Jun 10 '16 19:06

cmaynard


2 Answers

For Angular 2 and newer, the easiest way to add no-cache headers by overriding RequestOptions:

import { Injectable } from '@angular/core'; import { BaseRequestOptions, Headers } from '@angular/http';  @Injectable() export class CustomRequestOptions extends BaseRequestOptions {     headers = new Headers({         'Cache-Control': 'no-cache',         'Pragma': 'no-cache',         'Expires': 'Sat, 01 Jan 2000 00:00:00 GMT'     }); } 

Module:

@NgModule({     ...     providers: [         ...         { provide: RequestOptions, useClass: CustomRequestOptions }     ] }) 
like image 120
Vitaliy Ulantikov Avatar answered Sep 18 '22 18:09

Vitaliy Ulantikov


Today, I also had this problem, (damn IE). In my project, I use httpclient, that hasn't BaseRequestOptions. We should use Http_Interceptor to resolve it!

import { HttpHandler,     HttpProgressEvent,     HttpInterceptor,     HttpSentEvent,     HttpHeaderResponse,     HttpUserEvent,     HttpRequest,     HttpResponse } from '@angular/common/http'; import { Observable } from 'rxjs/Observable';  export class CustomHttpInterceptorService implements HttpInterceptor {     intercept(req: HttpRequest<any>, next: HttpHandler):       Observable<HttpSentEvent | HttpHeaderResponse | HttpProgressEvent | HttpResponse<any> | HttpUserEvent<any>> {       const nextReq = req.clone({         headers: req.headers.set('Cache-Control', 'no-cache')           .set('Pragma', 'no-cache')           .set('Expires', 'Sat, 01 Jan 2000 00:00:00 GMT')           .set('If-Modified-Since', '0')       });        return next.handle(nextReq);   } } 

Module provide

@NgModule({     ...     providers: [         ...         { provide: HTTP_INTERCEPTORS, useClass: CustomHttpInterceptorService, multi: true }     ] }) 
like image 28
Jimmy Ho Avatar answered Sep 16 '22 18:09

Jimmy Ho