2016-11-25 14 views
1

私はいくつかのJSONを取得するために新しいwindow.Fetchメソッドを使用しています。これは、私がconsole.logでjsonデータを読むことができる約束オブジェクトを返します。角度2コンポーネント内でPromiseの結果を使用するにはどうすればよいですか?

角度コンポーネント内でfetchメソッドを使用すると、結果が返されたときに他のメソッドを呼び出すことができません。スコープが何らかの形で失われているようですか?

以下のコメントを参照してください:字句のコンテキストを維持するために

(function(app) { 

    app.Actorlist = 
    ng.core.Component({ 
     selector: 'actor-list', 
     templateUrl: './app/actorlist.component.html' 
    }) 
    .Class({ 
     constructor: function() { 
     }, 

     showActors: function(js) { 
      this.actorName = js.name; 
     }, 

     searchActor: function(){ 

     fetch('http://swapi.co/api/people/1/') 
      .then(function(response) { 
      return response.json(); 
      }) 
      .then(function(js) { 
      // this logs the json result correctly 
      console.log(js); 

      // error: showActors is not defined 
      showActors(js); 

      // error: this.showActors is not defined 
      this.showActors(js); 

      // should I use return? return to where? 
      return js; 
      }); 
     } 
    }); 

})(window.app || (window.app = {})); 
+1

['.bind()']( 'https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind)'にコールバックを 'this'にします。 –

+0

"this.showActors(js).bind(this);"を使用すると、私は同じエラー "this.showActorsは関数ではありません"を取得します。私はまた、.bindがES6では必要なくなったと考えました... – Kokodoko

+1

'.then(function(){bind}(this))'でなければなりません。 – dfsq

答えて

2

使用arrow functionsを:

fetch('http://swapi.co/api/people/1/') 
    .then(function(response) { 
    return response.json(); 
    }) 
    .then(js => { 
    this.showActors(js); 
    }); 

あなたはまた、本当にあなたがこれを使用しないよう約束コールバックから何かを返す必要はありません。さらに何らかの方法でチェーンを約束する。

+0

ただし、このブラウザをサポートする必要がある場合は、矢印機能はIE11ではサポートされていません。 –

+0

ありがとうございました! – Kokodoko

関連する問題