Reputation: 3002
I want to call a method from a angular2 service from outside and from that method to call other method from same class or to have access to variables inited in construct.
I am using ngZone to make a method accesible from outside. My class looks like this:
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")
}
})
And I call this method from outside like this:
window.Component.zone.run(function(){
window.Component.onCallFromOutside(e);
})
And this is the error I get:
EXCEPTION: TypeError: this.inisdeCall is not a function
I am using angular2 in plain JavaScript
Upvotes: 0
Views: 759
Reputation: 202286
The problem here is that you reference a function so you lost the this
instance.
You could use the bind
method to bind your function to the this
object:
var Component1 = ng.core.Class({
constructor:[ng.core.NgZone, function(_ngZone) {
window.Component = {
onCallFromOutside: this.onCallFromOutside.bind(this), // <-------
zone: _ngZone
};
this.some_var = "AAA";
}],
(...)
Upvotes: 1