Angular 如何在发送API调用刷新数据之前清除可观察数组?
我有一个应用程序,它每x秒/分钟调用一次API,以获取最新数据。但是,我遇到了一个问题,即数据在刷新时不断翻倍。如何在获取最新值之前清除数据? api-call.service.ts 在我的other.component.ts中 每次调用api时,mapData[]的大小都会加倍。 如有任何帮助/信息,将不胜感激。 HSAngular 如何在发送API调用刷新数据之前清除可观察数组?,angular,timer,rxjs,observable,subscription,Angular,Timer,Rxjs,Observable,Subscription,我有一个应用程序,它每x秒/分钟调用一次API,以获取最新数据。但是,我遇到了一个问题,即数据在刷新时不断翻倍。如何在获取最新值之前清除数据? api-call.service.ts 在我的other.component.ts中 每次调用api时,mapData[]的大小都会加倍。 如有任何帮助/信息,将不胜感激。 HS private _earthquakeData$ = new ReplaySubject<EarthquakeResponse>(1); constru
private _earthquakeData$ = new ReplaySubject<EarthquakeResponse>(1);
constructor(private readonly httpClient: HttpClient) {
}
getEarthquakeData(): Observable<EarthquakeResponse> {
// return the subject here
// subscribers will will notified when the data is refreshed
return this._earthquakeData$.asObservable();
}
refreshEarthquakeData(): Observable<void> {
return this.httpClient.get<any>(this.url).pipe(
tap(response => {
// notify all subscribers of new data
this._earthquakeData$.next({
geometries: response.features.map(x => x.geometry),
properties: response.features.map(x => x.properties)
});
})
);
}
private destroyed$ = new Subject();
constructor(private readonly earthquakeService: EarthquakeService) {
}
ngOnInit() {
this.earthquakeService.getEarthquakeData().pipe(
takeUntil(this.destroyed$)
).subscribe(data => {
this.data = data;
});
timer(0, 10000).pipe(
takeUntil(this.destroyed$),
tap(() => this.refresh = true),
switchMap(() =>
this.earthquakeService.refreshEarthquakeData())
).subscribe(() => {
console.log('refreshed');
this.refresh = false;
});
this.today = new Date();
}
onRefresh() {
this.refresh = true;
console.log('refreshed');
this.earthquakeService.refreshEarthquakeData().subscribe(() => {
this.refresh = false;
});
}
ngOnDestroy() {
this.destroyed$.next();
this.destroyed$.complete();
}
ngOnInit() {
this.earthquakeService.getEarthquakeData().subscribe(data => {
this.data = data;
this.generateMapData();
});
}
generateMapData() {
for (const g of this.data.geometries) {
const tempData: any = {
latitude: g.coordinates[0],
longitude: g.coordinates[1],
draggable: false,
};
this.mapData.push(tempData);
}
console.log(this.mapData);
}
generateMapData() {
this.mapData = [];
//another way if js style notworking this.mapData = new Array<any>();
for (const g of this.data.geometries) {
const tempData: any = {
latitude: g.coordinates[0],
longitude: g.coordinates[1],
draggable: false,
};
this.mapData.push(tempData);
}
console.log(this.mapData);