2017-05-25 139 views
0

我正在研究一個函數,有人可以給出關於如何指定一個函數外面的函數的建議嗎? 在if語句中我想調用otherfunction()。Angular 2:Ts:嵌套函數

@Injectable() 
export class menuService { 
    constructor(){} 
    testing(){ console.log('something')} 
    loadwidget(){ 


      // not able to call this function 
      this.testing() 

    } 
} 

錯誤,我得到的是「this.testing是不是一個函數」

ERROR TypeError: this.testing is not a function 
    at Object.menuService.loadwidget (http://localhost:3000/main.bundle.js:755:14) 
    at Object.eval [as handleEvent] (ng:///AppModule/tbuttonsComponent.ngfactory.js:36:41) 
    at handleEvent (http://localhost:3000/vendor.dll.js:13146:138) 
    at callWithDebugContext (http://localhost:3000/vendor.dll.js:14354:42) 
    at Object.debugHandleEvent [as handleEvent] (http://localhost:3000/vendor.dll.js:13942:12) 
    at dispatchEvent (http://localhost:3000/vendor.dll.js:10121:21) 
    at http://localhost:3000/vendor.dll.js:10711:38 

https://plnkr.co/edit/XCHsu19UhR9wWxz4VLOx?p=preview

回答

1

這正是你應該如何在類中訪問其他方法,關閉this關鍵字。如果您正在使用上面的課程,那麼問題是沒有在customfunction()中的任何位置定義,因此錯誤。因此,otherfunction()中的console.log()聲明永遠不會有機會運行。

編輯:我看了一下你添加的Plunker,結果證明這是一個範圍問題。我更新了menuService類,則使用箭頭功能隱式綁定thismenuService,第三個按鈕開始按預期工作:

export class menuService { 
    constructor(){ 
    // I moved this into the constructor and updated loadingwidget below 
    this.menu = [{ 
     id: 1, 
     loadingwidget:() => { this.loadwidget(); }, 
    }]; 
    } 

    testing(){ 
    console.log('something'); 
    alert('something'); 
    } 

    loadwidget(){ 
    this.testing(); 
    } 
} 

這是你Plunker的工作版本:https://plnkr.co/edit/sF08cccRb2b0xkfTspVV?p=preview

+0

難道因爲它是注射劑嗎? –

+0

@ChrisTarasovs看看我的編輯,這不是一個@injectable問題,這是'this'沒有綁定到'menuService'的問題。 – IAmKale

0

你如何定義應該工作。如果otherfunction()未被調用,請檢查您是否有語句,也許比較不會返回您所期望的內容。

請看看這個plunker例如:https://plnkr.co/edit/4MWYDdeS5cCTDHI64HO2?p=preview

+0

我已經完全更新了我的方式,我得到它不是一個函數,但我正確地調用它。 –

+0

我已經更新了也在使用您的代碼的plunker示例。你會比較你的代碼?還請看看你在哪裏調用loadwidget()。 – hakany

+0

這裏更接近我明智的代碼:https://plnkr.co/edit/XCHsu19UhR9wWxz4VLOx?p=preview –

0

這是因爲注射的不是和你不需要注射也因爲你沒有任何東西注射到服務。所以你可以省略。但我可以看到有像這一個碼數問題,

menu = [ 
     { 
     id = 1, 
     loadingwidget: this.loadwidget 
     } 
    ] 

,它應該是

menu = [ 
     { 
     id:1, 
     loadingwidget: this.loadwidget 
     } 
    ] 

,它是不正確編譯。它工作得很好。