-1

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?

k.vincent
  • 3,743
  • 8
  • 37
  • 74
  • I think we should add a mandatory field, in case some users think they are better and down vote a question, so that they are forced to enter the reason for down voting. The main target of the SO platform is help and sharing knowhow, not "just" clicking some buttons silently. – k.vincent Apr 23 '20 at 09:49

1 Answers1

0

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!

k.vincent
  • 3,743
  • 8
  • 37
  • 74