Utilizing the same API across 3 components can lead to duplicate HTTP calls. To prevent this, I decided to cache the response using shareReply()
from RxJs so it can be reused wherever needed. Here's how I implemented it:
api-service.ts
getUsers(): Observable<any> {
let headers = new HttpHeaders();
headers = headers.set('app-id', '63b691428f53f6370fc9eed6');
return this.http.get(this.url, { headers }).pipe(
map((resp) => {
return resp;
}),
shareReplay()
);
}
test1-component
data$!: Observable<any>;
constructor(private api: ApiService) {}
ngOnInit(): void {
this.loadTest1Data();
}
loadTest1Data() {
this.data$.subscribe({
next: (response) => {
console.log('Loading data for Component - 1', response);
},
error: (error) => {
console.log('Error While Loading data for Component - 1', error);
},
complete: () => {
console.log('Success');
},
});
}
test2-component (test3-component also use the same code)
data$!: Observable<any>;
constructor(private api: ApiService) {}
ngOnInit(): void {
this.loadTest2Data();
}
loadTest2Data() {
this.data$.subscribe({
next: (response) => {
console.log('Loading data for Component - 2', response);
},
error: (error) => {
console.log('Error While Loading data for Component - 2', error);
},
complete: () => {
console.log('Success');
},
});
}
A problem occurred: reproducing HERE - Stackblitz
Cannot read properties of undefined (reading 'subscribe')
Can anyone help me understand what went wrong and how to fix it? Is there an alternative approach available that does not involve third-party state management tools?
Thank you in advance for your assistance.