Jayesh Ambali
Jayesh Ambali

Reputation: 221

Issue with MergeMap with forkJoin Angular 5

I am trying to execute 5 parallel http requests with mergeMap and forkJoin conditionally. For me only the first api is getting executed and rest of the apis are not triggering.

my function will execute first api and if it returns status as 'NOT_FOUND', then I need to execute another 5 apis and need to return the final result. If Iam getting status different from 'NOT_FOUND', need to just return the observable from first http request. I tried different options, but nothing seems to be working. Below shared code, Im getting "ERROR TypeError: Unable to get property 'map' of undefined or null reference"

public myPostWrapper( url, body, flag): Observable<any> {
 return this.http.post( url, body, { headers: this.headers } )
        .map(( out: any ) => {
            console.log( 'out', JSON.stringify( out ) );
            this.result = out;
        } )
        .mergeMap(( response: any ) => {
            console.log( 'response-inside', JSON.stringify( response ) );
            if ( this.result.status === 'NOT_FOUND' ) {
                return Observable.forkJoin(
                    response.map(( resp: any ) => {
                        return this.http.post(url, body, { headers: this.headers })
                            .map(( res: any ) => {
                                const section: any = res;
                                return section;
                            } );
                    } ),
                    response.map(( resp: any ) => {
                        return this.http.post(url, body, { headers: this.headers })
                            .map(( res: any ) => {
                                const section: any = res;
                                return section;
                            } );
                    } )
                );
            } else {
                return Observable.of( this.result );
            }
        } )
        .catch(( error: any ) => Observable.throw( error || 'Server error' ) 
);

}

Any help/direction would be greately appreciated. Note Im using Rxjs 5.52 with Angular 5

Upvotes: 0

Views: 1023

Answers (1)

Thor Jacobsen
Thor Jacobsen

Reputation: 8861

In the first map, where you set this.result, you don't return anything. That means, the following parts of the chain will operate on undefined. Add return out; to the first map operation, that should fix your issue.

...
return this.http.post( url, body, { headers: this.headers } )
    .map(( out: any ) => {
        console.log( 'out', JSON.stringify( out ) );
        this.result = out;
        return out; // <--- This return here
    } )
...

Optionally, you should replace all occurances of response in your mergeMap with this.result.

Upvotes: 2

Related Questions