当IE缓存ajax请求时,我遇到了一个众所周知的问题。

在JQuery中我们有$.ajaxSetup({ cache: false });
最常见的解决方案是更改每个请求的url .然而,对于这个问题有什么特定的解决方案吗?
使用Angular2和asp.net core
发布于 2016-04-08 13:40:31
在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。
发布于 2017-07-20 17:30:58
蒂埃里的解决方案可能是最好的,但如果你想要一种技术含量低、侵扰性低的方法,你可以编写一个函数,在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。该函数将在'clean‘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,然后在您想要使用它的时候调用这个值上的无缓存函数。但这有点草率。
https://stackoverflow.com/questions/36500804
复制相似问题