Vihung
Vihung

Reputation: 13407

How can I call a REST API early and often using RxJS and Angular 8?

I have a REST API that returns a list of values.

I would like to call it straight away to load values into a member variable of a component, and then refresh it again every five minutes.

Doing some preliminary research, I am doing the following;

In my service class:

getFooList(): Observable<Foo> {
  return interval(FIVE_MINUTES).pipe(
    switchMap(() => this.http.get<Foo>(url, HTTP_OPTIONS))
  );
}

and, this in my component

fooList: Foo[] = [];

ngOnInit(): void {
  this.loadFooList();
}

private loadFooList() {
  this._fooService.getFooList().subscribe(
    (fooList) =>  this.fooList = fooList,
    (err) => console.error(err)
  );
}

The problem with this is that the first call is not made until the first five minutes are up.

What option do I have for calling the API straight away, and then every five minutes? Other than moving the interval code into the component class (I'd like to keep it in the reusable singleton service), and calling the API once initially and then setting up the interval (that smacks of uneccesary code duplication).

Upvotes: 0

Views: 182

Answers (1)

mbojko
mbojko

Reputation: 14679

Use timer instead of interval: return timer(0, FIVE_MINUTES).pipe(// etc. (The 0 is the initial delay).

https://www.learnrxjs.io/learn-rxjs/operators/creation/timer

Upvotes: 2

Related Questions