2016-03-16 104 views
0

我想從外部的角度2服務調用方法,並從該方法調用同一類的其他方法或訪問構造中的變量。如何從外部調用angular2組件方法並參考此?

我正在使用ngZone製作一種可從外部訪問的方法。我的階級是這樣的:

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

回答

1

這裏的問題是,你引用一個函數,所以你失去了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"; 
    }], 
    (...)