I have a well-known problem when IE Caches ajax requests
In JQuery we have $.ajaxSetup({ cache: false });
Most common solution is to change url on each request... However is there any angular2-specific solution for this problem?
using Angular2
and asp.net core
Thierry's solution is probably best, but if you want a low-tech, less intrusive way you could write a function that appends a timestamp parameter to the URL..
utility-service.ts:
noCacheUrl( url: string): string{
const timestamp = "t=" + ((new Date()).getTime());
const prefix = ((url.indexOf("?") !== -1 ) ? "&" : "?");
return (url + prefix + timestamp);
}
... I defined my all of my URLs in an app-settings files. So, you could then use a get function to retrieve the URL.. that function would run the noCacheUrl function on the 'clean' URL..
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) {
}
}
.. then to use it you just inject the AppSettings class into your component and ask for the url using the name of the get function.
export class MyComponent{
constructor(private appSettings: AppSettings) {
}
getData(){
const url = this.appSettings.AUTH_URL;
}
}
The only downside I see to this is that you have to inject the appSettings class into every component you want to use it in whereas with regular static constants you don't. With static constants we lose the ability to run processing on the data at runtime so there's a trade. I guess you could define your URLs in a static const class and then call the no-cache function on the value whenever you want to use it.. but that's a little sloppy.
There is no native support of this within Angular2. You need to implement this by your own.
A possible approach would be to implement an HTTP interceptor and append a timestamp if the request with the URL has already been executed.
Here is a sample:
@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;
});
}
}
You can register this CustomHttp
class this way:
bootstrap(AppComponent, [
HTTP_PROVIDERS,
provide(Http, {
useFactory: (backend: XHRBackend, defaultOptions: RequestOptions) => new CustomHttp(backend, defaultOptions),
deps: [XHRBackend, RequestOptions]
})
]);
See this plunkr: https://plnkr.co/edit/Nq6LPnYikvkgIQv4P5GM?p=preview.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With