How to return additional values from flatMap in RxJs

喜夏-厌秋 提交于 2019-12-12 01:02:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!