Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over array created from subscribe function of Observable

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.

like image 331
Leth Avatar asked Mar 05 '26 02:03

Leth


1 Answers

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))
       });
   }
});
like image 174
Manuel Zametter Avatar answered Mar 06 '26 15:03

Manuel Zametter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!