dockerrrr
dockerrrr

Reputation: 297

Angular 2 observable array order

I'm creating a array of observables.

for (let i = 0; i < userinput.length; ++i) {
        const data = this.transformData(userinput[i]);
        observableBatch.push(this.http.post(this.submitApi, data, requestOptions).map(dataresponnse => dataresponnse.json() ,err => console.error(err))
          .catch(error =>  Observable.of(error) ));
      }
      return Observable.forkjoin(observableBatch);
The code works fine .But the order of the array is not correct .I want to get the result of the last http post ,but when i push(into the array) the index of the last http post is not predictable.Is there any way to acheive this ?

Upvotes: 1

Views: 320

Answers (2)

Aarsh
Aarsh

Reputation: 2595

Instead of using push you can use unshift. It will add your last HTTP post-call data in the first index. So you can easily predict the index of your last HTTP post.

Upvotes: 0

Michael Kang
Michael Kang

Reputation: 52867

Destructure the array so that its like you're passing the parameters to forkJoin one by one:

return Observable.forkJoin(...observableBatch);

For example, this equates to:

return Observable.forkJoin(obs1, obs2, obs3, obs4, etc);

The mapped value returned should be an array whose results are in the same order as they were passed:

observable.subscribe(t=> { console.log(t[0]) /*res1*/, 
                           console.log(t[1]) /*res2*/,
                           console.log(t[2]) /*res3*/,
                           console.log(t[3]) /*res4*/,
                           etc... })

Upvotes: 1

Related Questions