Using the ngOnDestroy() method on our Angular component we cancel http requests if they are still pending when leaving a page. On some pages we use a custom generic cache helper to prevent reloading data which are already loaded.
import { HttpClient } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { AsyncSubject } from "rxjs";
@Injectable()
export class HttpCacheHelper {
public cache = new Map<string, AsyncSubject<any>>();
public constructor(private readonly http: HttpClient) {
}
public get<T>(url: string): AsyncSubject<T> {
if (!this.cache.has(url)) {
const subject = new AsyncSubject<T>();
this.cache.set(url, subject);
this.http.get(url)
.subscribe((data:any) => {
subject.next(data as T);
subject.complete();
});
}
return this.cache.get(url);
}
}
If I unsubscribe from the AsyncSubject my http call is (of course) not cancelled. How to accomplish that?