【问题标题】:How can I call an Observable with timer inside of an Observable with typescript?如何在带有打字稿的 Observable 中调用带有计时器的 Observable?
【发布时间】:2019-02-01 23:05:58
【问题描述】:

我在 Angular 中有一个 http POST 调用,大约需要 15-20 秒才能完成。 在我的后端,我为前端的 post call 的进度条提供了一个计算值。

现在我想在 POST 调用启动后每 250 毫秒进行一次 http GET 调用,直到 post 调用完成。

我查看了 Rxjs 的操作员,但无法找到如何正确组合/管道它们的解决方案(例如计时器或间隔)

这是我当前的代码:

// this is the Observable which does the post call when subscribing
const x = this.apiService.importBackUp(this.backupList);

x.subscribe(); // here I want to subscribe to my GET call every 250ms until completion

apiService.ts:

importBackUp(backup: BackupList[]): Observable<any> {
    return this.httpClient.post(this.API_URL + '/Settings/import', backup)
      .pipe(
        catchError(this.handleError('Import Backup', null))
      );
}

getProgress(): Observable<number> {
    return this.httpClient.get<number>(this.API_URL + '/Settings/progress')
      .pipe(
        catchError(this.handleError('Get Import Progress', null))
      );
}

【问题讨论】:

  • 你试过.pipe(interval(250))吗?
  • 你的意思是const x = this.apiService.importBackUp(this.backupList).pipe(interval(250), this.apiService.getProgress());

标签: angular typescript rxjs observable


【解决方案1】:

试试这个

interval(250).pipe(
        mergeMap(()=>this.apiService.getProgress()),
        tap(progress=>do you process update ....),
        takeUntil(this.apiService.importBackUp(this.backupList))
        ).subscribe()

this.apiService.importBackUp(this.backupList).pipe(
withLatestFrom(
    interval(250).pipe(
    switchMap(()=>this.apiService.getProgress()),
    tap(progress=>do you process update ....),
    )
)
.subscribe()

【讨论】:

    猜你喜欢
    • 2021-11-12
    • 2016-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-18
    • 2018-05-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多