In our Angular component, we leverage the ngOnDestroy() method to handle canceling http requests that are still pending when navigating away from a page. To avoid reloading data that has already been fetched, we utilize a custom generic cache helper on certain pages.
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);
}
}
I'm facing an issue where unsubscribing from the AsyncSubject doesn't actually cancel my http call. How can I achieve proper cancellation in this scenario?