这是我需要实现的方案:
到目前为止,我已经能够创建以下内容:
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中,forkjoin的订阅中的“愿望”是我想在可观察对象中返回的值,但是我无法在此可观察对象中获取它们。因此,我应该使用什么代替“ tap”运算符。才能将forkJoin管道的结果放入可观察到的返回值中?
尝试将tap
for切换为,将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;
}),
);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句