![](/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.