Angular 2在完成后5秒重复forkJoin

时间:2017-10-27 19:39:28

标签: angular expand

我想每隔5秒重复一次forkJoin方法。 forkJoin完成后应启动5秒计时器并返回结果;

这是我目前的forkJoin:

  let getResult1 = this.myService.GetResult1(param1, param2);       // retrun Observable<Result1>
      let getResult2 = this.myService.GetResult2(param1, param3,param4);// retrun Observable<Result2>

       Observable.forkJoin(getResult1, getResult2)
            .subscribe(results => {
              this.result1 = results[0];
              this.result2 = results[1];
              .. start counting 5 seconds and then repeat this again and again
            },
            error => this.handleError(error));

我想要的时间表:

时间:0 - - 1 - - 2 - - 3 - - 4 - - 5 - - 6

行动:要求 - Res - - - - - - - - - - - - -Req -...

等等:|等待5秒-------&gt; |

3 个答案:

答案 0 :(得分:0)

使用间隔可观察:

Observable.interval(5000)
          .switchMap(t => 
               Observable.forkJoin(getResult1, getResult2))
          .subscribe(results => {
            this.result1 = results[0];
            this.result2 = results[1];
          },
          error => this.handleError(error));

这将每5秒产生一次请求,不一定在完成后5秒。但它应该足够接近。如果它必须完全是5秒钟,你需要采用不同的方法。

答案 1 :(得分:0)

我不确定这是否是最优雅的方式。拥有更多rxjs经验的人可能能够提供更清晰的解决方案,但我首先想到的是使用Subject来确定何时应该调用forkJoin。然后在forkJoin之后添加一个计时器来发出另一个请求。

url = 'http://url/CloudService/ReadText'
api_key = 'MY_API_KEY'
body = {
    'Text': 'Hello',
    'Speaker': 'Female1',
    'Format': 'mp3/32/m',
    'Quality': 'quality/normal',
    'APIKey': api_key
}
header = {
    'Content-type': 'application/json'
}

r = requests.post(url, data=json.dumps(body), headers=header)

这是一个演示plnkr(https://plnkr.co/edit/OaLIMxKKUqNXxcGp0HLW?p=preview),包括订阅清理以避免内存泄漏

答案 2 :(得分:0)

在完成回调方法中的代码后使用setTimeout

export class MyComponent {

  private refreshInterval: number;
  private timeoutId: any;

  public ngOnInit(): void {
    this.refreshInterval = 5000; // 5 seconds.
    this.refresh();
  }

  private refresh(): void {
    forkJoin(
      this.service1.doThis(),
      this.service2.doThat(),
      // More calls...
    ).subscribe(results => {
      this.data1 = results[0];
      this.data2 = results[1];
      // More stuff...

      this.timeoutId = setTimeout(() => this.refresh(), this.refreshInterval);
    });
  }

  public ngOnDestroy(): void {
    if (this.timeoutId) clearTimeout(this.timeoutId);
  }

}