如何从RxJs中的flatMap返回其他值

时间:2018-08-01 12:58:00

标签: javascript angular rxjs

在以下设置中,我需要从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};
}))

如何实现?

2 个答案:

答案 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);
});