Reputation: 785
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.
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.
Upvotes: 0
Views: 899
Reputation: 222582
this
refers to the function gets a this according to the calling context,
, not the networkLinkList
,
but the arrow functions
keep the this of the context of definition.
Use the arrow function in this case,
d3.selectAll(".njg-node").filter((d) => {
}
Upvotes: 1