RXJS - 多个连续的 http 请求

RXJS - multiple consecutive http requests

source<http>
  .pipe(
    switchMap(d => this.http.get(d))
      .pipe(
        switchMap(j => this.http.get(j))
      )
  )
  .subscribe()

您好,我需要连续发出 3 个 http 请求,其中每个调用都包含下一个调用的数据。嵌套开关映射是这种情况下的最佳做法吗?

您不需要嵌套它们。您可以简单地将它们链接起来:

source<http>
  .pipe(
    switchMap(d => this.http.get(d)),
    switchMap(j => this.http.get(j))
  )
  .subscribe()

除此之外,使用多个 switchMap 是可行的方法。

switchMap 是连续调用的更好选择。

    const first$: Observable<string> = of('first').pipe(tap(c => console.log(c)));
    const second$: Observable<string> = first$.pipe(
      switchMap(first=> {
        return of(first+ ' ' + 'second');
      })
    );
    const third$: Observable<string> = combineLatest(first$, second$).pipe(
      switchMap(([first, second]) => {
        return of(first + second + 'third');
      })
    );

    combineLatest(first$, second$, third$).subscribe(() => {});