简体   繁体   English

为什么我不能浏览自定义对象数组?

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

I have the following Interface in angular:我在 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:我还有一个服务,我调用 API 并获得结果,然后迭代结果以初始化上述接口的数组:

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:当我调用此服务并 console.log 结果时,我得到一个具有以下结构的对象数组:

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.我得到一个包含大约 50 个元素的数组作为返回,具有相同的结构。 The problem comes when I try to do a .forEach from that array.当我尝试从该数组中执行.forEach时,问题就来了。 The forEach is 'skipped', I put console.log inside and nothing shows. forEach 被“跳过”,我将 console.log 放在里面,没有任何显示。 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.谢谢你的时间。

Be aware of the fact that you populate your array inside the subscribe function.请注意,您将数组填充到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.要检查这一点,请将数组的迭代与它的console.log放在订阅中的res.feed.entry.forEach之后。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM