Reputation: 177
How to avoid multiple http requests when same component is used twice in template
https://stackblitz.com/edit/angular-8sgrgz
hello component is used twice in the template and its making calling service method for http data
return this.http
.get('https://api.openweathermap.org/data/2.5/weather?
q=London&appid=517c7bbf790248290ad52d57725c4d5f')
.map((res) => {return res.json()})
.catch((error:any) =>
Observable.throw(error.json().error || 'Server
error')).share();}
the http request should happen only once
but its happening more than once
Upvotes: 1
Views: 1325
Reputation: 10127
Add the Behaviour subject to hold your data once you fetch it:
private data$: BehaviorSubject<any> = new BehaviorSubject(null);
Add a function to get data:
getData() {
return this.data$.pipe(
switchMap(data => {
if (data) {
return of(data); // If data was saved, just return it (you're actually returning an observable of data, because switchMap needs observables to switch for every other observable emission)
} else {
return this.http.get("") // If it wasn't, make a new http request
.pipe(tap(newData => this.data$.next(newData))); // And save the data on the subject
}
})
);
}
Hope that helps.
Upvotes: 1