这是我需要实现的方案:
到目前为止,我已经能够创建以下内容:
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) }));
})
);
console.log中的forks订阅中的“愿望”是我想在可观察对象中返回的值,但是我无法在此可观察对象中获取它们。 所以我应该使用什么代替“ tap”运算符。能够将forkJoin管道的结果放入可观察到的返回值中?
答案 0 :(得分:1)
尝试将tap
切换为switchMap
,后者会切换到新的可观察对象。
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;
}),
);