Search code examples
angulartypescriptxmlhttprequestrxjs6

Why concatMap does not work for multiple requests at once?


I have an array of objects data/ids received as parameter in the function where I should execute a post request for each element/id:

fillProfile(users) {

    const requests = [];
    console.log( 'USERS.length:', users.length );
    requests.push( this.http.post( '/test/add', users[i] ) );

    for ( let i = 0; i < users.length; i++) {
        return this.http.post( '/test/add', users[i] ).pipe(
            map( (res) =>  {
                console.log( 'res: ', res );
                return res;
            }),
            catchError(err => {
                return throwError(err);
            })
        );
    }

It's working but it's not a good praxis and so fare I did search, it can be done via forkJoin or other operators. Have been trying these options/answers found in SO but unfortunately none of them did work.

One option I tried which doesn't work:

 ....
 return from(requests2).pipe(
     concatMap((request) => request.pipe(
         delay(500),
         map( res => {
             // console.log( 'res: ', res );
             return res;
         })
    ))
);

Any idea how to execute multiple requests and also get response and error of each one separately in a better approach?


Solution

  • Fixed. It was my mistake cause thinking in the wrong direction and also had a bug when creating array. The way how it works now:

    in service:

    getArrayIds(users) {
        this.observables = [];
        for ( const i in users) {
            this.observables.push( this.http.post( '/test/add', users[i] ) );
        }
    }
    
    
    fillProfile(users): Observable<any> {
        return from(this.observables).pipe(
            concatMap((request) => request.pipe(
                delay(10),
                map( res => {
                    return res;
                })
            ))
        );
    }
    

    in *.component.ts:

    ....
    public results$: BehaviorSubject<Array<any>> = new BehaviorSubject([]);
    
    ....
    this.surveyService.answerSurveyQuestions(body).subscribe(res => {
         console.log( 'response: ', res );
         this.results$.next(this.results$.getValue().concat(res));
    });
    

    Can even output the results$ in the View ans debug all the response. Thanks to this question and the answers there!