问题
I need to return an additional value other than Observable, key string from flatMap from below setup:
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());
Something like:
flatMap((key) =>{
var res = this.tradingService.getTradingData(key);
return {res,key};
}))
How to achieve this?
回答1:
Just use map ...
flatMap((key) =>{
return this.tradingService.getTradingData(key).pipe(map((res) => {
return {res,key};
}));
}))
ps: i am a bit confused: isnt flatMap deprecated and replaced my mergeMap, switchMap, ... ?
edit: apparently the problem was caused by using flatMap instead of mergeMap.
回答2:
You can destructur object as function parameters
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);
});
来源:https://stackoverflow.com/questions/51633903/how-to-return-additional-values-from-flatmap-in-rxjs