buttonClicked() {
let num = 0;
this.myService.myFirstMethod().subscribe(response=> {
num = response.result;
});
this.myService.mySecondMethod(num).subscribe(response=> {
console.log(response);
});
}
只有在回傳第一個方法時,如何才能呼叫第二個方法,像.then在 Promise 中一樣鏈接它們?
uj5u.com熱心網友回復:
您可以使用switchMap
buttonClicked() {
this.myService
.myFirstMethod()
.pipe(response => {
const num = response.result;
return this.myService.mySecondMethod(num)
})
.subscribe(response => {
console.log(response);
});
}
uj5u.com熱心網友回復:
您可以使用“高階映射運算子”(switchMap, mergeMap, concatMap, exhaustMap)將一個可觀察發射映射到另一個可觀察發射。
如果您myFirstMethod()只發出一個值,那么您使用哪一個并不重要,讓我們switchMap來看看這個例子:
buttonClicked() {
this.myService.myFirstMethod().pipe(
switchMap(num => this.myService.mySecondMethod(num))
).subscribe(secondResponse => {
console.log(secondResponse);
});
}
您傳遞一個函式,該函式回傳一個 observable 到switchMap. 這個“內部 observable ”將被switchMap 在內部訂閱(和取消訂閱)。然后發出來自“內部可觀察”的排放。因此,它本質上將可觀察的#1 的排放映射到可觀察的#2 的排放。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/442721.html
上一篇:Angular訂閱以等待回應
