Prevent IE11 caching GET call in Angular 2

前端 未结 7 678
甜味超标
甜味超标 2020-11-28 09:19

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

7条回答
  •  盖世英雄少女心
    2020-11-28 09:24

    A little late, but I ran into the same problem. For Angular 4.X I wrote a custom Http class to append a random number to the end to prevent caching by IE. It is based on the 2nd link by dimeros (What is httpinterceptor equivalent in angular2?). Warning: not guaranteed to be 100% bug free.

    import { Injectable } from '@angular/core';
    import { Observable } from 'rxjs/Observable';
    import { Http, Response, XHRBackend, RequestOptions, RequestOptionsArgs, 
    URLSearchParams } from '@angular/http';
    
    @Injectable()
    export class NoCacheHttp extends Http {
        constructor(backend: XHRBackend, options: RequestOptions) {
            super(backend, options);
        }
    
        get(url: string, options?: RequestOptionsArgs): Observable {
            //make options object if none.
            if (!options) {
                options = { params: new URLSearchParams() };
            }
            //for each possible params type, append a random number to query to force no browser caching.
            //if string
            if (typeof options.params === 'string') {
                let params = new URLSearchParams(options.params);
                params.set("k", new Date().getTime().toString());
                options.params = params;
    
            //if URLSearchParams
            } else if (options.params instanceof URLSearchParams) {
                let params = options.params;
                params.set("k", new Date().getTime().toString());
    
            //if plain object.
            } else {
                let params = options.params;
                params["k"] = new Date().getTime().toString();
            }
            return super.get(url, options);
        }
    }
    

提交回复
热议问题