Search code examples
angularangular5angular6angular-httpclientangular4-httpclient

Multiple Calls inside loop


I'm new with Angular so I need some help, My problem is to call http get I use service there is my first get

My first Service

getFirstData() { return this.http.get<FirstDataResults ('http://myurl.com/api/Classes/ads', httpOptions);

My component TS file

this.data.getFirstData().subscribe(
    data => {
        this.firsobjects = data.results;
    },
    err => console.error(err),
    () => this.getComplementData(this.firstobjects)
);

Until now always is fine can fetch my data and when it's completed i run the second function called getComplementData

My Second Service

getSecondData(idFirstObject: String) {
    return this.http.get<ComplementDataResults>(
  'http://myurl.com/api/Classes/Complement?' +
  'where={'"idFirstObject":"' + idFirstObject + '"}',
   httpOptions);
}

My component TS file

getComplementData(firsobjects) {
this.number = 0;
for (var _i = 0; _i < firsobjects.length; _i++) {
    this.data.getSecondData(firsobjects[_i].id).subscribe(
        (data) => {
            var a = (data.results);
            this.firsobjects[this.number].complements = a;
        }, err => console.log('error ' + err),
            () => console.log('Ok ')
        );
    }
}

I Have problem with this second function i can fetch all data but the problem is that the complement data are not ordered from what I understood of the http call inside my loop are parallel so async.

My question is, how I can run my http get inside the loop sync to get ordered results.

Thank you !


Solution

  • You should use rxjs' forkJoin

    getComplementData(firsobjects) {
        this.number = 0;
        let calls = [];
        for (var _i = 0; _i < firsobjects.length; _i++) {
            calls.push(this.data.getSecondData(firsobjects[_i].id));
        }
    
        forkJoin(...calls).subscribe(
            data => { // Note: data is an array now
                var a = (data[0].results);
                this.firsobjects[this.number].complements = a;
            }, err => console.log('error ' + err),
            () => console.log('Ok ')
        );
    }
    

    Something like that. Enjoy.