Typescript RXJS/Angular 6:Debounce/将多个请求分组为一个请求并超时
我需要通过唯一ID获取城市的天气数据。API有它的局限性,所以我需要将多个请求分组为一个请求Typescript RXJS/Angular 6:Debounce/将多个请求分组为一个请求并超时,typescript,rxjs,observable,angular6,rxjs6,Typescript,Rxjs,Observable,Angular6,Rxjs6,我需要通过唯一ID获取城市的天气数据。API有它的局限性,所以我需要将多个请求分组为一个请求 getWeatherByCityId(cityId: number): Observable<IWeatherData> { const cachedWeatherData = this.weatherCache.filter( (weatherData: IWeatherData) => weatherData.id === cityId );
getWeatherByCityId(cityId: number): Observable<IWeatherData> {
const cachedWeatherData = this.weatherCache.filter(
(weatherData: IWeatherData) => weatherData.id === cityId
);
this.getDebouncedDataTimer = timer(5000);
if (cachedWeatherData && cachedWeatherData.length !== 0) {
return of(cachedWeatherData[0]);
}
this.debouncedIds.push(cityId);
if (this.getDebouncedDataSubscription) {
this.getDebouncedDataSubscription.unsubscribe();
}
this.getDebouncedDataSubscription = this.getDebouncedDataByIds(cityId).pipe(
delay(5000)
).subscribe(data => data);
return this.getDebouncedDataSubscription;
}
getWeatherByCityId(cityId:number):可观察{
const cachedWeatherData=this.weatherCache.filter(
(weatherData:IWeatherData)=>weatherData.id==城市id
);
this.getDebouncedDataTimer=计时器(5000);
if(cachedWeatherData&&cachedWeatherData.length!==0){
返回(cachedWeatherData[0]);
}
这个.debouncedIds.push(cityId);
if(this.getDebouncedDataSubscription){
this.getDebouncedDataSubscription.unsubscribe();
}
this.getDebouncedDataSubscription=this.getDebouncedDataByIds(cityId).pipe(
延迟(5000)
).订阅(数据=>数据);
返回此.getDebouncedDataSubscription;
}
其想法是在5000ms后只执行一个请求,以同时获取多个城市的天气,而不是在检查缓存数据后执行多个请求
所以getWeatherByCityId方法应该被多次调用,getDeBouncedDataById应该只被调用一次,而不是重载API
问题在于,回报只能被观察到,而不能被订阅。我不能在管道内部使用map,因为在这种情况下我不能取消订阅
在这种情况下,我还应该为每个城市返回正确的值:
private getDebouncedDataByIds(cityId: number) {
return this.getWeatherByCityIds(debouncedIds).pipe(
map((weatherDataMultiple: HttpResponse<IWeatherDataMultiple>) => {
if (weatherDataMultiple.status === 200) {
this.weatherCache.push(...weatherDataMultiple.body.list);
return weatherDataMultiple.body.list.filter(
(weatherData: IWeatherData) => weatherData.id === cityId
)[0];
}
})
);
}
private GetDeBouncedDataById(城市ID:number){
返回此.getWeatherByCityId(DebouncedId).pipe(
地图((weatherDataMultiple:HttpResponse)=>{
如果(weatherDataMultiple.status==200){
this.weatherCache.push(…weatherDataMultiple.body.list);
返回weatherDataMultiple.body.list.filter(
(weatherData:IWeatherData)=>weatherData.id==城市id
)[0];
}
})
);
}
这样做的方法很少。您可以将其映射到函数外部或内部,就像您所做的那样。但是,我们的想法不是在函数内部订阅。您可以返回Observable并在调用方法中调用subscribe。Observable将返回订阅对象,您可以稍后取消订阅