【问题标题】:Proper way to prevent Angular2 http request caching in internet explorer (IE)在 Internet Explorer (IE) 中防止 Angular2 http 请求缓存的正确方法
【发布时间】:2016-07-29 18:55:08
【问题描述】:

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

最常见的解决方案是更改每个请求的 url... 但是有没有针对这个问题的 angular2-specific 解决方案?

使用Angular2asp.net core

【问题讨论】:

    标签: angular asp.net-core-1.0


    【解决方案1】:

    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;
        });
      }
    }
    

    你可以这样注册这个CustomHttp类:

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

    看到这个 plunkr:https://plnkr.co/edit/Nq6LPnYikvkgIQv4P5GM?p=preview

    【讨论】:

    • 有任何关于现在或将来支持此功能的消息吗?
    • ` urls: {string:string} = {};` 你将如何改变它以使用 angular 5 ?
    【解决方案2】:

    Thierry 的解决方案可能是最好的,但如果您想要一种技术含量低、侵入性较小的方法,您可以编写一个将时间戳参数附加到 URL 的函数..

    utility-service.ts:

    noCacheUrl( url: string): string{
        const timestamp = "t=" + ((new Date()).getTime());
        const prefix = ((url.indexOf("?") !== -1 ) ? "&" : "?");
    
        return (url + prefix + timestamp);
    }
    

    ...我在应用程序设置文件中定义了我的所有 URL。因此,您可以使用 get 函数来检索 URL。该函数将在“干净”URL 上运行 noCacheUrl 函数。

    app-settings.ts:

    import {UtilityService} from "../providers/utility-service";
    
    @Injectable()
    export class AppSettings {
        private static _AUTH_URL = "http://myurl.com";
    
        get AUTH_URL() {
            return this.utilityService.noCacheUrl(AppSettings._AUTH_URL);
        }
    
        constructor(private utilityService: UtilityService) {
        }
    }
    

    .. 然后要使用它,您只需将 AppSettings 类注入您的组件并使用 get 函数的名称请求 url。

    export class MyComponent{
        constructor(private appSettings: AppSettings) {
        }
    
        getData(){
            const url = this.appSettings.AUTH_URL;
        }
    }
    

    我看到的唯一缺点是您必须将 appSettings 类注入到您想要使用它的每个组件中,而使用常规静态常量则不需要。使用静态常量,我们失去了在运行时对数据进行处理的能力,因此需要进行交易。我想你可以在静态 const 类中定义你的 URL,然后在你想使用它时调用该值的 no-cache 函数。但这有点草率。

    【讨论】:

    • 它有一个权衡,但我喜欢它,因为它是更底层的解决方案。谢谢!
    猜你喜欢
    • 2013-10-24
    • 2011-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多