我尝试遵循这个示例、stackblitz和Observable文档,但似乎对我不起作用。坦率地说,我是RxJS的新手,不知道如何使用http和subscribe。盯着这个问题看了这么久,我的脑子都糊涂了。从本质上讲,我希望subscribe每隔一段时间就检查一次新数据。也许有比rxjs更好的方法?
import { Component, OnDestroy, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Weather } from './interface';
import { Observable } from 'rxjs/Observable';
import { interval } from 'rxjs';
import { take } from 'rxjs/operators';
import { Subject } from 'rxjs';
@Component({
selector: 'app-weather',
templateUrl: './weather.component.html',
styleUrls: ['./weather.component.css']
})
export class WeatherComponent implements OnInit {
weathers: any;
response: any;
// t = Observable.interval(1000).take(5);
// numbers = interval(1000);
// takeFourNumbers = interval(50000).pipe(take(2));
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);
// this.numbers.subscribe(x => console.log('Next: ', x));
});
}
}发布于 2019-04-04 05:50:28
您可以使用interval每秒发射一次,然后将每个发射转换为一个HTTP请求。
import { interval } from 'rxjs';
import { switchMap } from 'rxjs/operators';
interval(1000).pipe(
switchMap(() => this.http.get<Weather>(this.serviceUrl)),
).subscribe(result => {
// ...
});根据您想要的行为,您可能希望使用concatMap而不是switchMap。
https://stackoverflow.com/questions/55504798
复制相似问题