RxJS
Mon, 19 May 2025 12:54:24 GMT — Properties
Properties
| Key | Value |
|---|---|
| Identifier | rxjs |
| Name | RxJS |
| Type | Topic |
| Creation timestamp | Mon, 19 May 2025 12:54:24 GMT |
| Modification timestamp | Tue, 02 Sep 2025 09:20:22 GMT |
To chain Observables where one request depends on the response of another, use the RxJS switchMap operator:
Example 1
this.myService.fetchSomething().pipe(
switchMap((something) => {
return this.myOtherService.fetchSomethingElse(something);
})
).subscribe(
(somethingElse) => { ... }
);
Example 2
import { HttpClient } from '@angular/common/http';
import { switchMap } from 'rxjs/operators';
import { Observable } from 'rxjs';
// Assuming 'http' is an instance of HttpClient
function getFirstApiData(): Observable<any> {
return http.get('https://api.example.com/data1');
}
function getSecondApiData(id: string): Observable<any> {
return http.get(`https://api.example.com/data2/${id}`);
}
getFirstApiData().pipe(
switchMap(response1 => {
// Extract data needed for the second API call from response1
const id = response1.someId;
return getSecondApiData(id);
})
).subscribe(response2 => {
console.log('Result from second API:', response2);
});
To execute Observables in sequence when the requests are not dependent on each other's responses, use concatMap.
To execute Observables in parallel and return a collection of responses in the order that they finished, use mergeMap.
To execute Observables in parallel and preserve the order of responses, use forkJoin.
In most situations, you will want to use either switchMap or forkJoin.