Angular Js:如何将工厂数据提取到控制器

时间:2017-01-11 18:07:28

标签: angularjs

您好我正试图将我的角度js工厂数据拉到我的控制器, 如果有任何问题,请查看。

factory.js

.factory('History', ['$http', '$q', function ($http, $q) {

        function history () {

            // angular.extend(SearchOptions.getDefaults(), params, options);
            var deferred = $q.defer();

            $http({
                method: 'GET',
                url: '/res/orders/' + 31536427 + '/history-group'
            })
            .success(function (res) {
            // console.log(res);

            })
            .error(function (err) {
                // TODO error handler
                deferred.reject(err);
            });

            return deferred.promise;
        }

        return {
            history: history
        };
    }]);

controller.js

.controller('HistoryCtrl', ['$scope', '$state', '$stateParams', 'History', function($scope, $state, $stateParams, History) {

      History.history().then(function(res) {
          console.log(res);
          $scope.history = res.body;
          console.log($scope.history);

        }, function(err) {
          // TODO error handler
          console.log(err);

        })
        .finally(function(err) {

        });



  }]);

2 个答案:

答案 0 :(得分:3)

您需要在“历史记录”工厂的成功功能中传递响应,如下所示:

.success(function (res) {
   // console.log(res);
   deferred.resolve(res);
})

答案 1 :(得分:1)

您的代码的问题是您在成功回调函数中获取数据后没有解决承诺。如下所示在.success回调函数中解析它:

deferred.resolve(res);

很少有人会改进您的代码:

    默认情况下,
  1. $http Angular中的服务会返回一个promise。因此,您不必使用promise 明确构建$q,这是反模式Deferred anti-pattern) 。只需从服务本身返回$http对象即可 工作。执行return $http()相当于代码中的return deferred.promise()

  2. .successDeprecation Notice)的最新版本(1.6)中
  3. .errorAngularJs回调已弃用。使用它们的缺点是它们不可链接,因为它们忽略了返回值。因此,最好使用.then代替。

  4. 应用上述更改后,您的服务可以重构为以下内容:

    .factory('History', ['$http', function ($http) {
    
        function history () {
            return $http({
                         method: 'GET',
                         url: '/res/orders/' + 31536427 + '/history-group'
                   })
                   .then(successCallback, errorCallback);
         }
    
       function successCalback (res) {
             return res;
       }
    
       function errorCalback (err) {
             return err;
       }
    
        return {
            history: history
        };
    }]);