[英]Angular 4 error: Cannot read property 'push' of undefined
I am working on an Angular 4 app, where I am trying to push data into an array, but keep getting the error ERROR TypeError: Cannot read property 'push' of undefined
even though I initialized the array. 我正在使用Angular 4应用,正在尝试将数据推送到数组中,但始终收到错误
ERROR TypeError: Cannot read property 'push' of undefined
即使初始化数组,也ERROR TypeError: Cannot read property 'push' of undefined
。
Here's the code: 这是代码:
import {Component, OnInit} from '@angular/core';
declare let d3:any;
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
//Initialized array here
networkLinkList: Array<any> = [];
ngOnInit() {
this.networkGraph();
}
networkGraph() {
d3.netJsonGraph("../assets/json/network.json",
{
onClickNode: (url, opts) => {
this.highlightNodes(url, "nodes", true);
}
}
);
}
highlightNodes(url, type, initial) {
let url_children = url.children;
if(type === "nodes") {
let clicked_node_object = {
name: url.name,
description: url.description,
level: url.level,
link: url.url
};
//Push here is working fine
this.networkLinkList.push(clicked_node_object);
//Can see the array values here
console.log(this.networkLinkList);
d3.selectAll(".njg-node").filter(function(d) {
if(url_children.length > 0) {
for(let child=0; child<url_children.length; child++) {
if(d.id == url_children[child]) {
//Can see the all the values here
console.log(d.name + ", " + d.description + ", " + d.level + ", " + d.url);
let child_node_object = {
name: d.name,
description: d.description,
level: d.level,
link: d.url
};
//Push here is throwing the error
this.networkLinkList.push(child_node_object);
}
}
}
return ((url.children.length > 0 && (d.level === url.level + 1)));
});
}
}
Please help me resolve this issue, as I am not sure why the error is being thrown, even if the array is initialized. 请帮助我解决此问题,因为即使数组已初始化,我也不确定为什么会引发错误。
this
refers to the function gets a this according to the calling context,
, not the networkLinkList
, this
是指function gets a this according to the calling context,
,而不是networkLinkList
。
but the arrow functions
keep the this of the context of definition. 但是
arrow functions
保留了定义上下文的this。
Use the arrow function in this case, 在这种情况下,请使用箭头功能,
d3.selectAll(".njg-node").filter((d) => {
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.