首页 > 解决方案 > RxJS 延迟 switchMap 新的 observable 执行

问题描述

在我的 Angular 项目中,我正在进行一些 HttpClient 调用,响应后我需要检查它的主体并执行另一个 HttpClient 调用,具体取决于第一个响应。另外我需要延迟一些时间来执行第二个 HttpClient 调用。

我可以使用switchMap运算符来做到这一点,但我想知道如何以正确的方式延迟第二次 http 调用。

这是一个非常简单的例子:

export class AppComponent  {
  ngOnInit() {
    this.execute().subscribe(r => console.log(r))
  }

  execute(): Observable<string> {
    return this.http1Call().pipe(switchMap((r) => {
     // Checking if 2d http call must be executed or not
      if (r === '1st call') {
        console.log('---Invalid 1st call, executing 2d')
        // TODO: Is that correct way to execute http2Call with delay ???
        return of({}).pipe(delay(3000), switchMap(() => this.http2Call()))
      }

      return of(r);
    }));
  }

  http1Call(): Observable<string> {
    return of('1st call').pipe(delay(1000));
  }

  http2Call(): Observable<string> {
    console.log('------Inside http2Call')
    return of('--------2d call response').pipe(delay(3000));
  }
}

标签: angularrxjs

解决方案


你所拥有的基本上没问题,你可以简化(或者更明显)你延迟的部分:

return timer(3000).pipe(switchMapTo(this.http2Call()))

timer()一个参数只会在延迟后发出一次。你也可以使用concatMap/concatMapTo代替,switchMap/switchMapTo因为在这种情况下你永远不会切换任何东西(timer只发出一次然后完成)。


推荐阅读