繁体   English   中英

AngularJS的承诺?

[英]AngularJS Promises?

我正在使用angular-fullstack创建一个应用程序。 在我的应用程序中,我使用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);})();

这样做时,我收到未定义this.data的错误消息。 我知道这是异步调用的本质,但是我该如何解决呢?

谢谢

在严格模式下.then函数内部未定义this关键字。 设置一个局部变量以在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);})();

同时不建议使用 .success方法。 使用.then代替。

暂无
暂无

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

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