3

I have this code that gets some data from a MongoDB and saves it in an array in my component.

this.laugService.getAllLaug().subscribe(laug => {
  this.laugs = laug; //save posts in array
});

this.laugs.array.forEach(element => {
  this.modelLaugs.push(new Laug(element.navn, element.beskrivelse))
});

After that i want to save this data to a different array, where i create new instances of my model "Laug". For this i am using a foreach loop, however i am getting an error when running this code:

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 
'forEach' of undefined
TypeError: Cannot read property 'forEach' of undefined

I am certain that i receive the data from the DB, however i am unsure why my array is undefined at this point.

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
Leth
  • 1,033
  • 3
  • 15
  • 40
  • 2
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – dfsq May 30 '17 at 08:04

1 Answers1

2

Your subscription is asynchronous. The laugs property may not be set when you are trying to iterate. Just put the forEach code inside the subscribe callback:

this.laugService.getAllLaug().subscribe(laug => {
   this.laugs = laug; //save posts in array

   if (this.laugs && this.laugs.array) {
       this.laugs.array.forEach(element => {
          this.modelLaugs.push(new Laug(element.navn, element.beskrivelse))
       });
   }
});
Manuel Zametter
  • 309
  • 1
  • 8