RXJS - multiple consecutive http requests

限于喜欢 提交于 2020-01-15 04:40:09

问题


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

Hello, I need to make 3 http requests consecutively where each call contains data for the next call.. are nested switch maps the best practice for this case?


回答1:


You don't need to nest them. You can simply chain them:

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

Apart from that, using multiple switchMap is the way to go.




回答2:


switchMap is better option for consecutive calls.

    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(() => {});


来源:https://stackoverflow.com/questions/59570873/rxjs-multiple-consecutive-http-requests

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!