Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

angular - How to make an http call every 2 minutes with RXJS?

I have a service that will make a call to my rest service every 2 minutes. On my service I have the following function

  getNotifications(token: string) {
     const body = 'xxxxxxxxx=' + token;
     return this.http.post('/rest/ssss/ddddddd/notificationcount', body, this.options)
          .map((res) => res.json());
  }

On my component I call my service function to call the API.

this.notificationService.getNotifications(this.token).subscribe((data) => {
  console.log(data);
});

I want to make this call every 2 minutes, what is the best way to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since you are already using Observables, simply make full use of it :) Obersvable.interval() is your good friend here:

In your component, do this:

Observable
    .interval(2*60*1000)
    .timeInterval()
    .mergeMap(() => this.notificationService.getNotifications(this.token))
    .subscribe(data => {
        console.log(data);
    });

Explanation:

  1. .interval() creates an observable that emits an event every 2 minutes.
  2. .timeInterval() convert an Observable that emits items into one that emits indications of the amount of time elapsed between those emissions.
  3. .mergeMap() then wraps your each and every of service call, transform the results into an observable and return it. This ensure that the your service call at 0th, 2nd, 4th, 6th....minute is called synchronously. (think of there is a lot of .then()), i.e, service at 2nd minute will only be called on after the 0th minute's call, and 4th will only after 2nd, and so on.
  4. .subscribe() finally you can subscribe to the data

Update:

If you are using pipeable operators (rxjs5 and above), simply pipe the operators instead of chaining them:

interval(2 * 60 * 1000)
    .pipe(
        mergeMap(() => this.notificationService.getNotifications(this.token))
    )
    .subscribe(data => console.log(data))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...