简体   繁体   English

AngularJS的承诺?

[英]AngularJS Promises?

I am using angular-fullstack to create an app. 我正在使用angular-fullstack创建一个应用程序。 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): 在我的应用程序中,我使用Yelp API获取搜索结果,并将其存储在变量中(注意:this.searchTerm通过HTML中的ng-model进行了更改):

'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);})();

When I do so, I get an error that this.data is not defined. 这样做时,我收到未定义this.data的错误消息。 I understand that this is do to the nature of async calls, but how can I fix this? 我知道这是异步调用的本质,但是我该如何解决呢?

Thanks 谢谢

The this keyword is undefined inside a .then function in strict mode. 在严格模式下.then函数内部未定义this关键字。 Set a local variable to reference the this binding inside the then function. 设置一个局部变量以在then函数中引用this绑定。

'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);})();

Also the .success method is deprecated . 同时不建议使用 .success方法。 Use .then instead. 使用.then代替。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM