【问题标题】:How to continue poll an API and cancel the polling if a condition is not met如果不满足条件,如何继续轮询 API 并取消轮询
【发布时间】:2017-05-14 10:40:23
【问题描述】:

这里,如果待处理的服务 > 0,我想调用一个服务(http api)来获取新的状态。我为此编写了以下代码:

counter = 1;
getDetatils(){
  this.myService.getDetails().subscribe(services => {
    this.services = services;
    if(this.services.pending.length > 0 && counter <= 10){
      this.getDetails(); // if list of pending item is > 0, do query again.
      counter ++;
    }
})

以上代码,继续运行getDetails函数,除非挂起的服务列表为0(最多10次)。

但不知何故,我对上面的代码结构不满意。第一件事我不想每秒都在轮询。可能会在 5 点之后进行投票。不知何故,我讨厌使用 Timeout。

我在这里尝试使用 Observable,但对 angular2 不熟悉,不确定它的确切用法。

所以我的问题是,我可以在这里使用 Observable 吗,它可以同时处理间隔和最大尝试?如果是,那么如何?以及如果不满足某些条件我将如何取消它。

【问题讨论】:

  • 如果问题不清楚,请告诉我...

标签: angular observable angular2-services


【解决方案1】:

是否可以将待处理请求列表转换为 Observable?

class MyPendingService {
  private pending: Subject<any> = new Subject();

  get pendingRequests(): Observable<any> {
    return this.pending.asObservable();
  }

  queueRequest(x: any) {
    this.pending.next(x);
  }
}

// Somewhere else in your codebase you consume your observable
// ...

pendingService.pendingRequests.subscribe((next) => {
  // Replace this with your logic
  console.log("pending", next);
});

// In another place, you produce pending pending requests
// ...

pendingService.queueRequest("1");
pendingService.queueRequest("2");

查看这个 plunker 以获得最小的示例实现:https://embed.plnkr.co/9fLBH3YA7BlQw6ndZCFp/

【讨论】:

    猜你喜欢
    • 2015-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-22
    • 1970-01-01
    • 2019-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多