获取数据后的角度服务/工厂返回

时间:2014-09-07 23:58:34

标签: json angularjs q

我知道这与使用$ q和promises有关,但我已经使用了几个小时,但仍然无法弄清楚它应该如何与我的例子一起使用。

我有一个包含我想要的数据的.json文件。我有一个id的人名单。我希望有一个服务或工厂,我可以用一个参数来查询'http.hget我有一个json文件,根据参数过滤它,然后将它发送回我的控制器。

angular
  .module("mainApp")
  .controller('personInfoCtrl',['$scope', '$stateParams', 'GetPersonData', function($scope, $stateParams, GetPersonData) {

    $scope.personId = $stateParams.id; //this part work great

    $scope.fullObject = GetPersonData($stateParams.id);
    //I'm having trouble getting ^^^ to work.  

    //I'm able to do
    //GetPersonData($stateParams.id).success(function(data)
                 //                      { $scope.fullObject = data; });
    //and I can filter it inside of that object, but I want to filter it in the factory/service
  }]);

在我的main.js里面我有

//angular.module(...
//..a bunch of urlrouterprovider and stateprovider stuff that works
//
}]).service('GetPersonData', ['$http', function($http)
{
  return function(id) {
      return $http.get('./data/people.json').then(function(res) {
        //I know the problem lies in it not 'waiting' for the data to get back
        //before it returns an empty json (or empty something or other)
        return res.data.filter(function(el) { return el.id == id)
      });
    }
}]);

过滤的语法和一切都在控制器中运行时很好,但我想在几个控件中使用相同的代码,所以我试图将它分解为服务(或工厂,我只是想要控制器要“干净”看。)

我真的希望能够将“GetPersonData”注入控制器,然后调用GetPersonData(personId)来获取json

1 个答案:

答案 0 :(得分:2)

您似乎是服务中过滤器功能的语法问题。

.service('GetPersonData', ['$http', function($http){
  return function(id) {
     return $http.get('./data/people.json').then( function (res) { 
           return res.data.filter(function(el) { return el.id == id });
      });
}}]);

但是对于原始问题,您无法真正访问从函数返回的success承诺的$q属性,因为不存在此类属性,它仅存在于直接返回的承诺上通过http函数。所以你只需要使用then在控制器中链接它。

 GetPersonData($stateParams.id).then(function(data){ $scope.fullObject = data; });

如果您要从服务中返回return $http.get('./data/people.json'),则会看到http的自定义承诺方法successerror