2016-07-15 8 views
0

私は、Angular 2とコールバックを使用して結果を返すGoogle Apiを使用してアプリケーションを作成しています。角2:どのようにコールバックの結果をコンポーネントに返すことができますか?

結果がコンポーネントに返されないようです。 Typescriptが「これ」を引き継ぎ、コールバック関数コンテキストの結果をコンポーネントのクラスコンテキストに戻す方法がわかりません。ここで

は、基本的なサンプルコードです:

@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; 
 
      }); 
 
      
 

 
     }

関連する問題