在Internet Explorer(IE)中防止Angular2 http请求缓存的正确方法

Bri*_*irs 10 asp.net-core-1.0 angular

当IE缓存ajax请求时,我有一个众所周知的问题 在此输入图像描述 在JQuery中我们有 $.ajaxSetup({ cache: false });

最常见的解决方案是在每个请求上更改URL ...但是,是否存在针对此问题的特定于angular2的解决方案?

使用Angular2asp.net core

Thi*_*ier 9

Angular2中没有本机支持.你需要自己实现这个.

一种可能的方法是实现HTTP拦截器,如果已经执行了带有URL的请求,则附加时间戳.

这是一个示例:

@Injectable()
export class CustomHttp extends Http {
  urls: {string:string} = {};

  get(url: string, options?: RequestOptionsArgs): Observable<Response> {
    if (this.urls[url]) {
      options = options || {};
      options.search = options.search || new URLSearchParams();
      options.search.set('timestamp', (new Date()).getTime());
    }

    return super.get(url, options).do(() => {
      this.urls[url] = true;
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

您可以这样注册此CustomHttp课程:

bootstrap(AppComponent, [
  HTTP_PROVIDERS,
  provide(Http, {
    useFactory: (backend: XHRBackend, defaultOptions: RequestOptions) => new CustomHttp(backend, defaultOptions),
    deps: [XHRBackend, RequestOptions]
  })
]);
Run Code Online (Sandbox Code Playgroud)

请参阅此plunkr:https://plnkr.co/edit/Nq6LPnYikvkgIQv4P5GM p = preview .