GEVS
GEVS

Reputation: 51

ForEach inside API does not work properly

I am using angualr 4.

i have an array.

Here is my array;

this.bookings = [
    {
     'id':'dsjdsfhkdsjhfjkds01'
    },
    {
     'id':'dsjdsfhkdsjhfjkds01'
    }
]

I need retrieve data from database based on id.

Here is my script.

let scope = this;
scope.bookings.forEach(function(BookingItem){
  var bId = BookingItem.id;
  console.log("BId",bId);
  scope.Bservice.getbooking(scope.at,bId).subscribe(booking => {
    var responseVal = booking;
  })
})

I need like forEach Take on firstvalue then get retrive data from database.After going to second value of booking then get data from database.

But i consoled value of bId.

ForEach taken on id values one by one After retreive data from database.

How can i fix this pblm.

Kindly advice me,

Thanks.

Upvotes: 0

Views: 118

Answers (2)

Pranay Rana
Pranay Rana

Reputation: 176906

I am not understading you code at full but you have to do like this

You have to loop throught bookings array and than in argument of foreach you need vriable name not name of you class ,

Another thing is if you go in loop, you last returned value from ajax request will override vlaue of your variable , so better to store response in array thats why below code use array to store you response for each id.

let responseFromServer = new Array<any>();    

this.bookings.forEach((bookingItem) => {
   var bId=bookingItem.id;
   console.log("BId",bId);
   scope.Bservice.getbooking(scope.at,bId).subscribe(booking=>{
      let response = new ResponseFromServer();
      responseFromServer.Add(booking);
   });
});

Upvotes: 1

Sravan
Sravan

Reputation: 18647

Since the api call response takes some time, you should wait for the response untill it is recieved.

You can use Observable forkJoin which works like a promise and processes all requests in loop and returns response.

import {Observable} from 'rxjs/Rx';

let observables = new Array();

this.bookings.forEach(function(booking){
    observables.push(this.Bservice.getbooking(this.at,booking.id));
})

Observable.forkJoin(observables).subscribe(
    res => console.log(res),
    error => console.log('Error: ', error)
);

Here is a documentation for forkJoin

Upvotes: 0

Related Questions