Angular 2 subscribed call function inside for loop

I have a function with a subscription to a service inside:

selectCar(carNumber) {
  this.carService.getCarByNumerator(carNumber)
    .subscribe( (car) => {
                  console.log(carNumber);
                  //more stuff here
                },
                (err) => console.log(err)
               );
}

      

I want to call this function inside a for loop like this:

for(let carNumber of carNumbers) {
    this.selectCar(carNumber);
}

      

The problem is that sometime this works as I expect, but sometimes the order is not the same as the list.

eg. list:

45
67
89

      

but when I look in the console I see the following:

67
89
45

      

How can I get the for loop not to move to the next element until the current function call has completed?

+3


source to share


2 answers


I think it flatMap

will help you in this case.



Observable.of(carNumbers)
.flatMap(term => this.selectCar(term))
.subscribe( (car) => {
        console.log(carNumber);
        //more stuff here
    },
    (err) => console.log(err)
);

      

+2


source


If you need to efficiently wait for everyone getCarByNumerator()

to complete before processing your list of data, you can use forkJoin .

let carNumbers = [1, 2, 3];
let observables = carNumbers.map(carNumber => this.carService.getCarByNumerator(carNumber));

// forkJoin the array/collection of observables
let source = Rx.Observable.forkJoin(observables);

// subscribe and sort combined array/collection prior to additional processing
source.subscribe(x => console.log(x.sort((a, b) => a - b));

      



Here is a JS Bin demonstrating the functionality. This example shows the various delays for returning data from the "API".

Hope this helps!

+2


source







All Articles