问题
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