[英]RxJs equivalent of promise chain
當鏈接帶有諾言的API調用時,我這樣做:
this.http.get('/api/hello').toPromise().then(res => {
return this.http.get('/api/there/' + res.id).toPromise()
}).then(res => {
console.log('res from 2nd call', res)
}).catch(err => {
console.log('err', err)
})
當第二個響應需要第一個響應中的數據才能進行創建時,如何使用Observables這樣鏈接API調用?
TIA
您應該使用flatMap
請訪問此URL https://stackblitz.com/edit/angular-6-rxjx-stuff 。 我已經創建了這個項目來測試RxJS。
您可以看到以下功能。
test__flatMap() {
const post$ = this.getPosts();
const users$ = this.getUsers();
const users2$ = this.getUsers();
post$.pipe(
flatMap(data => {
console.log('data 1 >>> ', data);
return users$;
}),
flatMap(data => {
console.log('data 2 >>> ', data);
return post$;
}),
).subscribe(data => { console.log(`In the end >>> `, data); });
}
mergeMap
是一個選項:
this.http.get(/api/hello')
.pipe(mergeMap((s) => {
return s;
}),
mergeMap((res) =>{
const url ='/api/there/' + res.id;
return this.http.get(url).pipe(map((res) => {
return res;
}));
}))
.subscribe(res => {
console.log(res);//final response
},
undefined,
() => console.log('complete'));
在第一個推送數據之后,使用switchMap
執行另一個http.get。 switchMap
的優點是,當父級推送新數據時,它將取消所有未決的內部請求。
const request$ = this.http.get('pathto/api').pipe(
switchMap((res) => {
return this.http.get(`another/api/${res.id}`)
})
);
request$.subscribe(innerRequestData => {
// do whatever you want
});
別忘了訂閱,因為否則就很冷了 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.