如何使用 RXJS 每 2 分钟进行一次 http 调用? [英] How to make an http call every 2 minutes with RXJS?

查看:16
本文介绍了如何使用 RXJS 每 2 分钟进行一次 http 调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个服务,它会每 2 分钟调用一次我的休息服务.在我的服务中,我有以下功能

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());
  }

在我的组件上,我调用我的服务函数来调用 API.

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

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

我想每 2 分钟打一次电话,最好的方法是什么?

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

推荐答案

既然你已经在使用 Observables,那就充分利用它吧:) Obersvable.interval() 是你的好朋友:

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);
    });

说明:

  1. .interval() 创建一个 observable,它每 2 次发出一个事件分钟.
  2. .timeInterval() 将发出项目的 Observable 转换为一个发出指示之间经过的时间量的指示排放.
  3. .mergeMap() 然后包装您的每一个服务调用,将结果转换为一个 observable 并返回它.这确保您在第 0、2、4、6 分钟的服务呼叫被称为同步.(想想有很多.then()),即第2分钟的服务只会在第0分钟的调用后才会被调用,第4分钟会在第2分钟之后才会调用,以此类推.
  4. .subscribe() 终于可以订阅数据了
  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

更新:

如果您使用可管道操作符(rxjs5 及以上),只需管道操作符而不是链接它们:

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))

这篇关于如何使用 RXJS 每 2 分钟进行一次 http 调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆