[英]Returning an Observable from Angular method including pipe, switchMap, forkJoin
[英]Angular: return value from forkJoin inside pipe of other observable
這是我需要實現的場景:
到目前為止,我已經能夠創建以下內容:
public getWishlist ( receiver : Person) : Observable<Wish[]>{
return this.http$.get<IWishlistResponse[]>(environment.apiUrl + 'wishlist/' + receiver.id).pipe(
map( (response) => {
let wishes: Wish[] = [];
response[0].wishes.forEach((wish) => {
wishes.push(new Wish(
wish._id,
wish.title,
wish.price,
null,
wish.url
));
});
return wishes;
}),
tap( (wishes) => {
let wishStateObservables = wishes.map(wish => this.http$.get<wishStatus>(environment.apiUrl + 'wish/' + wish.id + '/state').pipe(catchError(() => of(null))));
forkJoin(wishStateObservables)
.pipe(
map(states => {
states.forEach((state, index) => {
wishes[index].status = state;
});
return wishes;
})
).subscribe((wishes => { console.log(wishes) }));
})
);
訂閱 forkjoin 的 console.log 中的“願望”是我想在我的 observable 中返回的值,但我無法在這個 observable 中得到它們。 那么我應該使用什么來代替 'tap' 運算符。 能夠將 forkJoin 管道的結果放在我返回的 observable 中?
嘗試為switchMap
切換tap
,它會切換到一個新的 observable。
import { switchMap } from 'rxjs/operators';
...
public getWishlist ( receiver : Person) : Observable<Wish[]>{
return this.http$.get<IWishlistResponse[]>(environment.apiUrl + 'wishlist/' + receiver.id).pipe(
map( (response) => {
let wishes: Wish[] = [];
response[0].wishes.forEach((wish) => {
wishes.push(new Wish(
wish._id,
wish.title,
wish.price,
null,
wish.url
));
});
return wishes;
}),
switchMap( (wishes) => { // change to switchMap to switch to new observable
let wishStateObservables = wishes.map(wish => this.http$.get<wishStatus>(environment.apiUrl + 'wish/' + wish.id + '/state').pipe(catchError(() => of(null))));
return forkJoin(wishStateObservables); // add return here to return for the switchMap
}),
map(states => { // remove the inner pipe from the forkJoin and put the pipe in outer pipe
states.forEach((state, index) => {
wishes[index].status = state;
});
return wishes;
}),
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.