2017-10-18 55 views
0

我有打字稿項目和更具體的和Angular應用程序。在打字稿中的新類中的方法中創建方法

我有我的類稱爲測試(你可以假設它的一個組件在角度),它有權訪問http服務,通常使用像這樣.http('/端點')。subscribe(response => {}) ;

我需要在兩者之間添加一些邏輯並將其分解爲單獨的方法(代碼比我的示例稍微複雜一點)。

export class Test { 

init() { 
    this.http.get('/endpoint').map(this.transform); 
} 

transform(data) { 
    // more logic here in isolated scope 

    this.accessOutside(data); // I cannot access this method, isolated scope. 
    // How to break down some logic into separate methods to access them 
    // or how to create it new method within method? 

    return data 
} 

accessOutside(data) { 
    // more logic 
} 

}

當我打電話this.http.get(「/端點」)。圖(this.transform)我的「改造」方法被隔離,並具有測試類內沒有接入的其它方法,但如何訪問它或如何在變換方法內創建方法?

回答

1

當您通過transform功能到map功能這樣

this.http.get('/endpoint').map(this.transform);

你逝去的 transform功能,它沒有的 this概念的副本

。因此,當map函數調用transform函數的副本時,它的上下文將默認爲window對象。因此,在transform方法的副本中,它將在window對象上查找名爲accessOutside的函數。

解決這個問題的最簡單方法如下使用lambda功能:

this.http.get('/endpoint').map(data => this.transform(data));

由於arrow funcitons獲得他們定義的背景下,範圍map調用箭頭功能時,this將指您的實例Test而不是window

+0

完美。正是我想要的。謝謝! –