使用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] 删除。
我来说两句