【问题标题】:AngularJS : Returning .then() response to controller propertyAngularJS:返回 .then() 对控制器属性的响应
【发布时间】:2015-09-25 06:02:51
【问题描述】:

我正在使用工厂来检索数据,使用$httpcontrollerAs 功能注入我的视图。如果不使用$scope,我在将$http 响应数据返回到我的控制器中的属性时遇到问题。

我的工厂

myApp.factory('Topics', function ($http, $q) {
    var service = {},
        _error = 'Oh no! Something went wrong. Please check back later.';


    service.getTopics = function () {
        var deferred = $q.defer();

        $http.get(_url).success(function (resp) {
            deferred.resolve(resp);
        }).error (function () {
            deferred.reject(_error);
        });
        return deferred.promise;
    }

    return service;
});

我的控制器

 myApp.controller('TopicsCtrl', function (Topics) {
    this.topics = (function () {
        return Topics.getTopics().then(function (resp) {
            console.log(resp);
            return resp;
        });
    })();
}

我的观点

<h1>{{ top.topics }}</h1>

就像我说的,我在配置为top 的路由中使用controllerAs。控制器中的console.log 记录了我要查找的内容,但topics 的值在注入视图时为空。留下我和 {}。

附:据我了解$http$q 的抽象,这让我想知道在这个例子中使用$q 是否是不必要的。

【问题讨论】:

    标签: angularjs angularjs-service angular-promise angularjs-http


    【解决方案1】:

    以下应该有效:

      myApp.controller('TopicsCtrl', function (Topics) {
        Topics.getTopics().then(function (resp) {
          this.topics = resp;
        }.bind(this));
      });
    

    然后通过 top.topics 在你的视图中访问它。

    编辑:另外,您的服务中不需要 $q 是正确的。您可以直接返回 $http.get:

    service.getTopics = function() {
        return $http.get(_url);
    };
    

    【讨论】:

      【解决方案2】:

      你所做的是用一个 promise 初始化 top.topics。但是角度视图不能用承诺做任何事情。他们需要的是实际数据,当 promise 被解决时可以访问。所以你需要的是:

      // oh the joys of this...
      var that = this;
      
      Topics.getTopics().then(function (resp) {
          console.log(resp);
          that.topics = resp;
      });
      

      请注意,您可以在服务中使用承诺链:

          return $http.get(_url).then(function (resp) {
              return resp.data;
          }).catch(function() {
              return $q.reject(_error);
          });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-08-17
        • 2016-01-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-07
        相关资源
        最近更新 更多