2016-11-25 69 views
1

我正在使用新的window.Fetch方法來獲取一些JSON。這將返回一個promise對象,從中我可以用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