首页 > 解决方案 > 如何在带有打字稿的 Observable 中调用带有计时器的 Observable?

问题描述

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

标签: angulartypescriptrxjsobservable

解决方案


尝试这个

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

推荐阅读