Reputation: 71
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?
Upvotes: 2
Views: 4449
Reputation: 1
Or a more imperative approach in an async method:
const result1: string = await firstValueFrom(this.http.get<string>(url, {headers}));
const result2: number = await firstValueFrom(this.http.post<number>(url2, result1, {headers}));
const result3: string = await firstValueFrom(this.http.post<string>(url3, result2, {headers}));
Upvotes: 0
Reputation: 142
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(() => {});
Upvotes: 1
Reputation: 5418
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.
Upvotes: 7