Javascript D3.js Angular CLI,tick()方法中的作用域丢失
大家好, 我正在尝试使用该组件将D3可视化网络图集成到Angular CLI项目()中 下面是角度分量: 当web应用程序加载时,它也会加载图形,但它根本不可见: 例如,当我在tick()方法中控制台记录this.path时,即使它是在appendGraph()方法中创建的,它也会给我未定义的信息。这是的一个变体。D3的强制布局将使用Javascript D3.js Angular CLI,tick()方法中的作用域丢失,javascript,angularjs,d3.js,graph,angular-cli,Javascript,Angularjs,D3.js,Graph,Angular Cli,大家好, 我正在尝试使用该组件将D3可视化网络图集成到Angular CLI项目()中 下面是角度分量: 当web应用程序加载时,它也会加载图形,但它根本不可见: 例如,当我在tick()方法中控制台记录this.path时,即使它是在appendGraph()方法中创建的,它也会给我未定义的信息。这是的一个变体。D3的强制布局将使用setTimeout()来安排其计时,这会导致tick()函数在实际执行时具有错误的范围 看看这一点,它说明了这个问题 但是,与上面的链接问题相反,D3调用se
setTimeout()
来安排其计时,这会导致tick()
函数在实际执行时具有错误的范围
看看这一点,它说明了这个问题
但是,与上面的链接问题相反,D3调用setTimeout()
,而不是您自己的代码,这需要另一种解决方法来保留您需要的范围。在这种情况下,您可以使用闭包在tick()
方法中保留对this
的引用:
tick() {
let self = this; // close over this
return function() {
// the function uses self throughout, which still references the instance of your class
self.path.attr("d", self.linkArc);
self.circle.attr("transform", self.transform);
self.text.attr("transform", self.transform);
}
}
除了这些调整之外,您还需要更正force布局的初始化,以调用.tick()
,作为一个生成器,返回实际的tick处理程序函数,该函数包含对类实例的此
范围的引用
forceLayout() {
this.force = d3.layout.force()
//...omitted for brevity
.on("tick", this.tick()) // Notice the parentheses after tick
.start();
}
我在这里设置了一个完整的工作演示
tick() {
let self = this; // close over this
return function() {
// the function uses self throughout, which still references the instance of your class
self.path.attr("d", self.linkArc);
self.circle.attr("transform", self.transform);
self.text.attr("transform", self.transform);
}
}
forceLayout() {
this.force = d3.layout.force()
//...omitted for brevity
.on("tick", this.tick()) // Notice the parentheses after tick
.start();
}