0

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

7 Comments

Doesn't work Argument of type '(key: string) => void' is not assignable to parameter of type '(value: string, index: number) => ObservableInput<{}>'.
what is the returntype of getTradingData?
It returns Observable<any>
You are right as mentioned here, " flatMap is an alias for mergeMap!" and once I changed from flatMap to mergeMap. It worked. Thanks a ton! You might want to change ur answer to use mergeMap.
Do you still have the import statement for the flatMap? Could it be that you were importing it from the wrong location?
|
0

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

3 Comments

Already tried this. Error: Argument of type '(key: string) => { res: Observable<any>; key: string; }' is not assignable to parameter of type '(value: string, index: number) => ObservableInput<{}>'
Pls validate it doesn't work, as I mentioned I get the error as in my previous comment.
You need to turn off type check for this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.