如何从外部调用angular2组件方法并引用它?
How to call angular2 component method from outside and have reference to this?
我想从外部调用 angular2 服务的方法,然后从该方法调用同一方法的其他方法 class 或访问构造中初始化的变量。
我正在使用 ngZone 使一个方法可以从外部访问。我的 class 看起来像这样:
var Component1 = ng.core.Class({
constructor:[ng.core.NgZone, function(_ngZone) {
window.Component = {
onCallFromOutside: this.onCallFromOutside,
zone: _ngZone
};
this.some_var = "AAA";
}],
onCallFromOutside: function(){
console.log("Called onCallFromOutside")
console.log(this.some_var) // This is null
this.inisdeCall() // Here I get error: EXCEPTION: TypeError: this.inisdeCall is not a function
}
inisdeCall: function(){
console.log("Called inisdeCall")
}
})
然后我像这样从外部调用这个方法:
window.Component.zone.run(function(){
window.Component.onCallFromOutside(e);
})
这是我得到的错误:
EXCEPTION: TypeError: this.inisdeCall is not a function
我在普通中使用 angular2 JavaScript
这里的问题是您引用了一个函数,所以您丢失了 this
实例。
您可以使用 bind
方法将您的函数绑定到 this
对象:
var Component1 = ng.core.Class({
constructor:[ng.core.NgZone, function(_ngZone) {
window.Component = {
onCallFromOutside: this.onCallFromOutside.bind(this), // <-------
zone: _ngZone
};
this.some_var = "AAA";
}],
(...)
我想从外部调用 angular2 服务的方法,然后从该方法调用同一方法的其他方法 class 或访问构造中初始化的变量。
我正在使用 ngZone 使一个方法可以从外部访问。我的 class 看起来像这样:
var Component1 = ng.core.Class({
constructor:[ng.core.NgZone, function(_ngZone) {
window.Component = {
onCallFromOutside: this.onCallFromOutside,
zone: _ngZone
};
this.some_var = "AAA";
}],
onCallFromOutside: function(){
console.log("Called onCallFromOutside")
console.log(this.some_var) // This is null
this.inisdeCall() // Here I get error: EXCEPTION: TypeError: this.inisdeCall is not a function
}
inisdeCall: function(){
console.log("Called inisdeCall")
}
})
然后我像这样从外部调用这个方法:
window.Component.zone.run(function(){
window.Component.onCallFromOutside(e);
})
这是我得到的错误:
EXCEPTION: TypeError: this.inisdeCall is not a function
我在普通中使用 angular2 JavaScript
这里的问题是您引用了一个函数,所以您丢失了 this
实例。
您可以使用 bind
方法将您的函数绑定到 this
对象:
var Component1 = ng.core.Class({
constructor:[ng.core.NgZone, function(_ngZone) {
window.Component = {
onCallFromOutside: this.onCallFromOutside.bind(this), // <-------
zone: _ngZone
};
this.some_var = "AAA";
}],
(...)