在模板中两次使用相同组件时如何避免多个http请求
https://stackblitz.com/edit/angular-8sgrgz
hello组件在模板及其对http数据的调用服务方法中使用了两次
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
答案 0 :(得分:1)
添加“行为”主题,以便在获取数据后保存数据:
private data$: BehaviorSubject<any> = new BehaviorSubject(null);
添加获取数据的功能:
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
}
})
);
}
希望有帮助。