Angular 4错误:无法读取未定义的属性“推”
问题描述:
我正在处理Angular 4应用程序,我尝试将数据推入数组,但即使我已初始化数组,但仍然收到错误ERROR TypeError: Cannot read property 'push' of undefined
。Angular 4错误:无法读取未定义的属性“推”
下面的代码:
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)));
});
}
}
请帮我解决这个问题,因为我不知道为什么被抛出的错误,即使该数组初始化。
答
this
指function gets a this according to the calling context,
,而不是networkLinkList
,
但arrow functions
保持清晰的背景下的这一点。
使用箭头功能在这种情况下,
d3.selectAll(".njg-node").filter((d) => {
}
使用'.filter((d)=> {'代替'.filter(函数(d){' – yurzui
@yurzui奏效!!莫非请详细说明,在这种情况下箭头功能如何提供帮助? – starlight
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_functions#No_binding_of_this'箭头功能不会自行创建这个,封闭执行上下文的这个值被使用了' – yurzui