【发布时间】:2019-04-10 00:12:16
【问题描述】:
我有以下显然需要改进的代码。它使用间隔发出重复的http get请求。是否有另一种 rxjs 方法来改进此代码?我在间隔之外发出第一个 http 请求的原因是我注意到间隔首先延迟然后响应数据。所以第一个请求规避了延迟。
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));
}
}
【问题讨论】:
-
您可以创建注入 HttpClient 而不是 Weather 组件的 WeatherService。 WeatherService 可能被注入到 WeatherComponent。
-
我不确定 WeatherService 注入是什么意思。我是 Angular 新手。
-
试试
timer。例如。timer(0, 5*60*1000)。它将立即进行首次发射。
标签: angular rxjs observable