I have developed a REST API that retrieves a list of values.
My goal is to immediately invoke this API to fetch values and store them in a component's member variable. Subsequently, I plan to refresh the data every five minutes.
Upon conducting some preliminary exploration, here is my approach:
Within my service class:
fetchFooList(): Observable<Foo> {
return interval(FIVE_MINUTES).pipe(
switchMap(() => this.http.get<Foo>(url, HTTP_OPTIONS))
);
}
In addition, within my component:
fooItems: Foo[] = [];
ngOnInit(): void {
this.loadData();
}
private loadData() {
this._fooService.fetchFooList().subscribe(
(fooItems) => this.fooItems = fooItems,
(err) => console.error(err)
);
}
The issue with this setup is that the initial API call is delayed until after the first five minutes elapse.
What are the alternatives for invoking the API immediately and then subsequently at five-minute intervals? I aim to avoid relocating the interval
logic to the component class (as I prefer to maintain it in the reusable singleton service), as well as executing the API call once initially followed by setting up the interval (which seems unnecessary and overly duplicative).