2016-07-15 73 views
0

我正在使用Angular 2和一個使用回調返回結果的Google Api編寫應用程序。Angular 2:如何將回調結果返回給組件?

我似乎無法得到結果返回到組件。 Typescript已經接管'this',我不確定如何從回調函數上下文返回Component的類上下文。

下面是基本示例代碼:

@Component({ 
    selector: '...', 
    viewProviders: [...], 
    templateUrl: '...', 
    directives: [...], 
    providers: [...] 
}) 
export class TestComponent { 
    new google.visualization.Query('...') 
    .send(function handleResponse(response : any){ 
     let datatable = response.getDataTable(); 
     ... 
     results.push(item); 
     } 

     this.viewCollection = results; //this no longer refers to the TestComponent 
    }); 
... 
} 

回答

1

您必須使用 「胖箭頭()=>」。它是在EcmaScript6中添加的,並替代了其他功能關鍵字。在類型位置中,=>定義了一個函數類型,其中參數位於=>的左側,返回類型位於右側。

的脂肪箭頭的動機是:

  1. 你並不需要繼續輸入功能(所以,這將是匿名的)

  2. 它詞法抓住了這個

  3. 的意義
  4. 它詞彙捕獲參數的含義

與此代碼段

@Component({ 
    selector: '...', 
    viewProviders: [...], 
    templateUrl: '...', 
    directives: [...], 
    providers: [...] 
}) 
export class TestComponent { 
    new google.visualization.Query('...') 
    .send((response : any)=> { 
     let datatable = response.getDataTable(); 
     ... 
     results.push(item); 
     } 

     this.viewCollection = results; //this will refer to the TestComponent 
    }); 
... 
} 

希望你能得到你的答案:)

更新代碼
0

如果要保留的上下文中,使用脂肪箭頭語法()=> {}而不是函數表達。

這裏是我如何與箭頭語法重寫你的組件:

export class TestComponent { 
 
     send() { 
 

 
     new google 
 
      .visualization.Query('...') 
 
      .send((response: any) => { 
 
      let datatable = response.getDataTable(); 
 
      response.forEach(item => { 
 
       results.push(item); 
 
      }); 
 
      this.viewCollection = results; 
 
      }); 
 
      
 

 
     }