Javascript 如何在角度2分量中使用Promise结果?
我正在使用新的window.Fetch方法获取一些JSON。这将返回一个promise对象,我可以使用console.log从中读取json数据 但是,如果我在一个角度组件中使用fetch方法,那么当返回结果时,我将无法调用其他方法。似乎范围不知何故丢失了 见以下评论:Javascript 如何在角度2分量中使用Promise结果?,javascript,angular,Javascript,Angular,我正在使用新的window.Fetch方法获取一些JSON。这将返回一个promise对象,我可以使用console.log从中读取json数据 但是,如果我在一个角度组件中使用fetch方法,那么当返回结果时,我将无法调用其他方法。似乎范围不知何故丢失了 见以下评论: (function(app) { app.Actorlist = ng.core.Component({ selector: 'actor-list', templateUrl: './ap
(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 = {}));
用于保留词汇上下文:
fetch('http://swapi.co/api/people/1/')
.then(function(response) {
return response.json();
})
.then(js => {
this.showActors(js);
});
您也不需要从promise callback返回任何内容,因为您不会以任何方式进一步使用此promise链。您对
this
的回调。如果我使用“this.showActors(js.bind(this)”;“我得到相同的错误”this.showActors不是函数。我还认为在ES6中不再需要.bind…它应该是。然后(function(){…}.bind(this))
,但最好使用arrow函数。@Kokodokobind(this)
在ES6 arrow函数中不需要()=>{}
如果您按照下面的答案使用arrow函数,则不需要它。因为箭头函数没有自己的上下文。您不应该绑定正在调用的方法,而应该绑定回调。类似这样的东西:.then((函数(js){…}).bind(this))代码>。但请注意,如果您需要支持此浏览器,IE11不支持箭头功能。谢谢您解决了这个问题!