如何在角度2分量中使用Promise结果?

时间:2016-11-25 13:10:25

标签: javascript angular

我正在使用新的window.Fetch方法来获取一些JSON。这将返回一个promise对象,我可以使用console.log从中读取json数据。

但是如果我在角度组件中使用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 个答案:

答案 0 :(得分:2)

使用arrow functions保留词汇上下文:

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

您也不需要从promise回调中返回任何内容,因为您不会以任何方式进一步使用此承诺链。