本文介绍了如何使用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()
    .flatMap(() => this.notificationService.getNotifications(this.token))
    .subscribe(data => {
        console.log(data);
    });

说明:

  1. .interval()创建一个可观察到的对象,每2个对象发出一个事件分钟.
  2. .timeInterval()将发射项目的Observable转换为一个发出指示之间的时间流逝的指示排放.
  3. .flatMap()然后包装您的每一个服务调用,将结果转换为可观察的结果并将其返回.这确保在第0、2、4、6 ....分钟呼叫您的服务电话同步地. (考虑到很多.then()),即,仅在第0分钟的呼叫后才调用第二分钟的服务,而仅在第二分钟的呼叫后才调用4th,依此类推.
  4. .subscribe()最后您可以订阅数据
  1. .interval() creates an observable that emits an event every 2minutes.
  2. .timeInterval() convert an Observable that emits items into onethat emits indications of the amount of time elapsed between thoseemissions.
  3. .flatMap() then wraps your each and every of service call,transform the results into an observable and return it. This ensurethat the your service call at 0th, 2nd, 4th, 6th....minute is calledsynchronously. (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(
        flatMap(() => this.notificationService.getNotifications(this.token))
    )
    .subscribe(data => console.log(data))

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

08-15 20:22