![](/img/trans.png)
[英]how can I access the variables of a service in the template of a component in angular
[英]how can I access the variables of my current component in angular without using “this”
这个问题听起来有点奇怪,但我会解释原因。 我正在将d3.js与Angular结合使用。 一切都很好,但是在d3.js的逻辑内有时会发生一些事件,其中“ this”是与angular上下文不同的值。 因此,我想知道是否有一种方法可以通过以下方式直接访问在组件中定义的变量:
HomeComponent.myVar //HomeComponent name of my current component
代替
this.myvar
这是我使用d3.js的问题的示例
Node.on("mouseout", unfocus);
function unfocus(){
console.log(this); //problem context angular
}
Node.mouseover(function(d){
console.log(this); //this is not context angular, is a value of this event
console.log(HomeComponent.myvar); //not works, but is my idea
})
谢谢。
注释说明您可以使用另一种语法来访问this
语法:
Node.mouseover(d => {
console.log(this);
})
如果你真的想保持一些语法,我不建议,你可以存储this
另一个变量:
let self = this;
Node.mouseover(function(d){
console.log(self);
})
我不建议这样做,因为它更难理解,容易出错,而且并不总是清楚变量的范围。
尝试使用var / let / const关键字将变量放置在类范围之外。 您可以尝试使用不带“ this”的变量
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.