错误TypeError:无法读取未定义的属性“打开”

加勒特

使用Angular 6,我在服务中调用API,然后在控制器中订阅该服务。我成功获取了数据,但是我想在控制器中重组数据,以便稍后将其传递到Chart JS图表中。

这是我在控制器女巫中放入的方法中的代码,然后在OnInit方法中进行调用:

getStockData() {
  this.stocksService.getStockData()
    .subscribe(
      (response) => {
        for(var i = 0; i <= response.length; i++) {
          this.stockOpen.push(response[i]['open']); // Error points to this line
          console.log('Data: ', response[i]['open']); //This works
        }
      },
      (error) => console.error(error)
    );
}

我知道至少有一部分是有效的,因为我已经成功地合并了for循环中的数据,但是然后我收到一个似乎无法弄清的错误,因为当我进行操作时response[i]['open'],但是当我尝试将其推送时进入this.stockOpen错误。

在我看来,push方法是问题所在,但我似乎无法弄清楚如何正确或以其他方式进行操作。

这是错误:

ERROR TypeError: Cannot read property 'open' of undefined
    at SafeSubscriber._next (alpha.component.ts:26)
    at SafeSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub (Subscriber.js:195)
    at SafeSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next (Subscriber.js:133)
    at Subscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._next (Subscriber.js:77)
    at Subscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:54)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/map.js.MapSubscriber._next (map.js:41)
    at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:54)
    at XMLHttpRequest.onLoad (http.js:1055)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:421)
    at Object.onInvokeTask (core.js:3748)
山姆

你的for循环应该是i < response.length,不是<=


话虽如此,如果您只是推送到另一个数组,或者索引无关紧要,则不应使用for循环。for...of至少要使用循环:更好的方法是,[].map(或者,如果数组已经填充,则[].reduce使用起始值[或只是将它们组合起来。])

this.stockOpen = response.map(item => item.open);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

反应 - 错误:TypeError:无法读取未定义的属性(读取“then”)

“TypeError:无法读取未定义的属性(读取'hasOwnProperty')”错误

作为错误:TypeError:无法读取未定义的属性“位置”

TypeError中的错误:无法读取未定义的属性“标志”

错误TypeError:无法读取未定义的属性'length'

错误TypeError:无法读取未定义的属性“调用”

错误TypeError:无法读取角度未定义的属性'closeRow'

错误TypeError:无法读取未定义的属性“匹配”

nodejs 收到错误 TypeError:无法读取未定义的属性“then”

错误TypeError:无法读取未定义的属性'grower'

呈现错误:“ TypeError:无法读取未定义的属性'text'”

错误TypeError:无法读取未定义的属性'get'

错误TypeError:无法读取未定义的属性'nativeElement'

角度-错误TypeError:无法读取未定义的属性'title'

FormGroup错误TypeError:无法读取未定义的属性“ get”

错误TypeError:无法读取未定义的属性'firstName'

错误TypeError:无法读取未定义的属性'property'

reactjs错误-TypeError:无法读取未定义的属性“地图”

错误TypeError:无法读取未定义的属性'ngInjectableDef'

错误TypeError:无法读取未定义的属性“类别”

错误TypeError:无法读取未定义的属性'openDialogTEST'

错误TypeError:无法读取未定义的属性'formData'

TypeError:无法读取未定义反应错误的属性“名称”

错误TypeError:无法读取未定义的属性'Nom'

错误TypeError:无法读取未定义的属性“句柄”

VSCode + Pytest:“错误:TypeError:无法读取未定义的属性” $“

错误TypeError:无法读取未定义的属性'__source'

reactjs错误:TypeError:无法读取未定义的属性“ props”

TypeError:无法读取未定义的属性“ then”