我有以下明显需要改进的代码。使用interval进行重复的http get请求。有没有其他的rxjs方法来改进这段代码?我在interval之外发出第一个http请求的原因是,我首先注意到了interval的延迟,然后使用数据进行响应。因此,第一个请求绕过了延迟。
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Weather } from './interface';
import { Observable } from 'rxjs';
import { concatMap } from 'rxjs/operators';
import { interval } from 'rxjs';
export class WeatherComponent implements OnInit {
weathers: any;
response: any;
private serviceUrl = 'https://api.weather.gov/gridpoints/OKX/36,38/forecast';
n = 10000;
constructor(private http: HttpClient) {}
ngOnInit() {
this.response = this.http.get<Weather>(this.serviceUrl );
this.response.subscribe(
results => {
this.weathers = results.properties.periods.slice(0, 2);
});
// 5 minute interval
interval(5 * 60 * 1000).pipe(
concatMap( () => this.http.get<Weather>(this.serviceUrl) ),
).subscribe(results => this.weathers = results.properties.periods.slice(0, 2));
}
}发布于 2019-04-10 08:21:34
This answer已经为您的问题提供了答案,但我将保留此答案,因为如果应用不当,它可能会导致其他问题。
重构如下:
import {Subscription, timer} from 'rxjs';
const MILISECS_IN_5_MINS = 5 * 60 * 1000;
export class FooComponent {
private timerSub = Subscription.EMPTY;
...
ngOnInit() {
this.timerSub = timer(0, MILISECS_IN_5_MINS).pipe(
concatMap(() => this.http.get<Weather>(this.serviceUrl))
).subscribe(results => this.weathers = results.properties.periods.slice(0, 2));
}
ngOnDestroy(){
// Unsubscribe to avoid mem. leaks, as the timer stream is infinite
this.timerSub.unsubscribe();
}
...
}https://stackoverflow.com/questions/55602957
复制相似问题