角2的承诺? [英] Angular 2 Promises?
问题描述
我使用角fullstack创建一个应用程序。在我的应用程序,我使用Yelp API来获取搜索结果,我想在一个变量来存储(注:this.searchTerm在HTML通过NG-模式改变):
I am using angular-fullstack to create an app. In my app, I use the Yelp API to get search results, which I want to store in a variable (Note: this.searchTerm is changed via an ng-model in the HTML):
'use strict';
(function() {
class MainController {
constructor($http) {
this.$http = $http;
this.awesomeThings = [];
this.searchTerm = "";
this.data = [];
}
addThing() {
this.$http.get('/api/messages/city/' + this.searchTerm).success(function(res){
this.data = res;
});
};
}
angular.module('nightlifeApp').controller('MainController', MainController);})();
当我这样做,我得到this.data没有定义的错误。我明白,这是做异步调用的本质,但我怎么能解决这个问题?
When I do so, I get an error that this.data is not defined. I understand that this is do to the nature of async calls, but how can I fix this?
感谢
推荐答案
的这个
关键字里面不确定的一个。然后
严格模式功能。设置一个局部变量来引用这个
的然后
函数内部具有约束力。
The this
keyword is undefined inside a .then
function in strict mode. Set a local variable to reference the this
binding inside the then
function.
'use strict';
(function() {
class MainController {
constructor($http) {
this.$http = $http;
this.awesomeThings = [];
this.searchTerm = "";
this.data = [];
}
addThing() {
var self = this;
this.$http.get('/api/messages/city/' + this.searchTerm).then (function(res){
self.data = res.data;
});
};
}
angular.module('nightlifeApp').controller('MainController', MainController);})();
另外, .success
方法的德precated 。使用。然后
代替。
这篇关于角2的承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!