2017-05-29 41 views
0

在組件:angular 2傳遞服務方法作爲組件中的參數?

myFunction(): void { 
    this.myOtherFunctoin(this._myService.serviceMethod); 
} 

private myOtherFunction(func : Function){ 
    func(); 
} 

在服務調用

serviceMethod(){ 
    this.somethingMethod(); // "this" is coming as undefined in debugger 
    this.somethingVariable = true; 
} 

我想傳遞方法,像在C# 委託參數難道我在這裏做得不對

回答

2

使用bind(this)或匿名箭頭包裝:

this.myOtherFunction(this._myService.serviceMethod.bind(this)) 
+0

我實際上已經厭倦了這一點,但由於某種原因,我沒有爲我工作,得到「這個」的參考是錯誤的。對我來說,它的工作原理是這樣的:** let tempVariable = this._myService.serviceMethod; this.myOtherFunction(this._myService.serviceMethod.bind(tempVariable)); ** – vaira

相關問題