I'm currently utilizing a BehaviorSubject in my service to retrieve data from the BackEnd, which I subscribe to in my mainComponent using the async pipe.
However, whenever I navigate to another subComponent and then return to my mainComponent by clicking a back button (which triggers Location.back()), it always performs a new request to fetch all the data from the BackEnd.
I suspect this behavior is due to the async pipe unsubscribing from the BehaviorSubject when exiting the mainComponent.
Is there a need to implement a caching strategy for this issue? Or can it be resolved by using a ReplaySubject with the size of the data fetched from the mainComponent?
Below is an excerpt of my code:
Service:
private subject$: BehaviorSubject<Setting[]> = new BehaviorSubject<Setting[]>([]);
fetchData() {
const fetch$: Observable <Setting[]> = this.getSettings().pipe(share());
fetch$.pipe(
map(allSettings => this.subject$.next(allSettings))
);
return fetch$;
}
MainComponent:
data: Observable<Setting[]>;
// Load Setting while starting
ngOnInit() {
this.data = this.apiService.fetchData();
}
MainComponent.html:
<tr *ngFor="let s of data | async">
<!--Do Something...-->
</tr>
SubComponent:
goBack(): void {
this.location.back();
}
Appreciate any assistance on this matter :)