Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why can't I navigate through array of custom objects?

I have the following Interface in angular:

export interface Example{
  id: string;
  name: string;
  num1: number;
  num2: number;
  num3: number;
}

I also have a Service where I call an API and obtain a result, and I iterate the result to initialize an array of the interface above:

res: any;
examples: Example[]
...
this.service.getData().subscribe(response => 
 {
   res = response;
 
   res.feed.entry.forEach((item: any) => {
     examples.push({
       id: item.id
       name: item.name
       ...
       });

When I call this service and I console.log the result, I get an array of objects with the following structure:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Array []
 0: Object {
    id: someID
    name: someName
    num1: 1
    num2: 2
    num3: 3
}
...

I get an array with around 50 elements as return with the same structure. The problem comes when I try to do a .forEach from that array. The forEach is ‘skipped’, I put console.log inside and nothing shows. I try to call it as follows:

this.examples.forEach((item)=>{
  console.log(item);
}

But nothing shows. How can I iterate the array to work with the information within? Why is this happening?

Thanks for your time.

>Solution :

Be aware of the fact that you populate your array inside the subscribe function.
If you iterate your array right after the subscription, there is a change that the subscription isn’t yet finished or started and therefore you don’t have any element inside your array.
To check this, put the iteration of the array with the console.log of it rignt after the res.feed.entry.forEach inside the subscription.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading