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) => {
       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:

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:


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.

Leave a Reply