0
我正在處理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)));
});
}
}
請幫我解決這個問題,因爲我不知道爲什麼被拋出的錯誤,即使該數組初始化。
使用'.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