2017-01-11 50 views
0

嗨我想拉我的角度js工厂数据到我的控制器, 请看看是否有任何问题。角度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) { 

     }); 



    }]); 

回答

3

您需要将在 '历史记录' 工厂为下文成功函数的响应:

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

问题你的代码是在成功回调函数中获取数据后,你没有解决承诺。默认返回一个承诺在角

  1. $http服务:解决它作为.success回调函数如下图所示:

    deferred.resolve(res); 
    

    几点来提高你的代码。因此,您不必明确构建promise使用$q这是一个反模式Deferred anti-pattern)。从服务本身返回$http对象将执行 作业。在您的代码中,执行return $http()相当于return deferred.promise()

  2. .success.error回调弃用的AngularJsDeprecation Notice)的最新版本(1.6)。使用它们的缺点是它们不能链接,因为它们忽略了返回值。因此,最好使用.then来代替。

应用上述变化,你的服务可以重构为以下:

.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 
    }; 
}]); 
相关问题