在以下设置中,我需要从key
返回{Observable,flatMap
字符串以外的其他值:
this.subscribeInit = this.tradingService.getInProgress()
.pipe(flatMap((s) => {
this.keys = s.map((tdi) => tdi.key);
return this.keys;
}),
flatMap((key) =>{
var res = this.tradingService.getTradingData(key);//returns `Observable<any>`
return res;
}))
.subscribe(res => {
console.log('Key is : ' + res.key);
},
undefined,
() => this.onComplete());
类似的东西:
flatMap((key) =>{
var res = this.tradingService.getTradingData(key);
return {res,key};
}))
如何实现?
答案 0 :(得分:2)
只需使用地图...
flatMap((key) =>{
return this.tradingService.getTradingData(key).pipe(map((res) => {
return {res,key};
}));
}))
ps:我有点困惑:不推荐使用flatMap并替换我的mergeMap,switchMap,...吗?
编辑:显然,问题是由使用flatMap而不是mergeMap引起的。
答案 1 :(得分:0)
您可以将对象分解为函数参数
this.subscribeInit = this.tradingService.getInProgress()
.pipe(flatMap((s) => {
this.keys = s.map((tdi) => tdi.key);
return this.keys;
}),
flatMap((key) =>{
var res = this.tradingService.getTradingData(key);
return {res,key}; // pack res and key into object
}))
.subscribe(({res,key}) => { // destructuring previously returned object
console.log('Key is : ' + res[key]);
},
undefined,
() => this.onComplete());
const val1 = 'some val1', val2 = 'some val2';
Promise.resolve({val1, val2}).then(({val1, val2}) => {
console.log(val1);
console.log(val2);
});