I have the following code that obviously need improvement. It uses interval to make repeated http get request. Is there another rxjs approach to improve this code? The reason I am making the first http request outside of interval is that I noticed the interval first delay then respond with the data. So the first request circumvent the delay.
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));
}
}