'How to call second method only after first method returns observable?
buttonClicked() {
let num = 0;
this.myService.myFirstMethod().subscribe(response=> {
num = response.result;
});
this.myService.mySecondMethod(num).subscribe(response=> {
console.log(response);
});
}
How can I call the second method only when the first one is returned, chain them like .then in Promise?
Solution 1:[1]
You can map an observable emission to another observable by using a "Higher order mapping operator" (switchMap, mergeMap, concatMap, exhaustMap).
If your myFirstMethod() only emits a single value, it doesn't really matter which one you use, let's us switchMap, for this example:
buttonClicked() {
this.myService.myFirstMethod().pipe(
switchMap(num => this.myService.mySecondMethod(num))
).subscribe(secondResponse => {
console.log(secondResponse);
});
}
You pass a function that returns an observable to switchMap. This "inner observable" will be subscribed (and unsubscribed) to internally by switchMap. Emissions from the "inner observable" are then emitted. So, it essentially maps an emission from observable #1 to emissions from observable #2.
Solution 2:[2]
You can use switchMap
buttonClicked() {
this.myService
.myFirstMethod()
.pipe(switchMap(response => {
const num = response.result;
return this.myService.mySecondMethod(num)
}))
.subscribe(response => {
console.log(response);
});
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | BizzyBob |
| Solution 2 |
