【问题标题】:Return Values from AngularJS servicesAngularJS 服务的返回值
【发布时间】:2015-08-05 08:50:34
【问题描述】:

我正在尝试将一个值从我的 AngularJs 服务返回到我的控制器,我将它传递到控制器内部。它确实传递了对象并将数据记录在控制台中。这是我的代码:

angular.module('demoService',[])
.factory('myService',
function($http) {
return {
    getAll: function (items) {
        var path = "http://enlytica.com/RSLivee/rest/census"
        $http.get(path).success(function (items) {

        console.log(items.Tweets[1].FAVOURITE_COUNT);

       });
    }
}
});

如何在函数调用时返回“items.Tweets[1].FAVOURITE_COUNT”。

提前致谢

【问题讨论】:

    标签: jquery angularjs http service return


    【解决方案1】:

    您可以对查询的数据创建一个promise,通过使用then方法,getAll会在API响应之前知道要做什么。

    angular.module('demoService')
    .factory('myService', ['$http', 
        function ($http) {
    
            function getAll (items) {
                var path = "http://enlytica.com/RSLivee/rest/census"
                return $http.get(path).then(
                    function (res) {
                        return res;
                     });
            }
    
            return {
                getAll: getAll;
            }
    
        }
    
    }];
    

    【讨论】:

      【解决方案2】:

      一种方法是创建一个承诺并在请求成功时解决它。不要忘记以其他方式拒绝它。

      angular.module('demoService',[])
      .factory('myService',
      function($q, $http) {
      return {
          getAll: function (items) {
              var defer = $q.defer();
              var path = "http://enlytica.com/RSLivee/rest/census"
              $http.get(path).success(function (items) {
      
                defer.resolve(items.Tweets[1].FAVOURITE_COUNT);
                console.log(items.Tweets[1].FAVOURITE_COUNT);
      
             });
      
             return defer.promise;
          }
      }
      });
      

      或者你可以从 $http.get 返回承诺:

       return $http.get(path);
      

      由于方法是调用getAll

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-10-29
        • 1970-01-01
        • 2014-09-02
        • 2023-03-31
        • 2019-01-02
        • 1970-01-01
        • 2013-04-29
        • 1970-01-01
        相关资源
        最近更新 更多