【问题标题】:Angular service/factory return after getting data获取数据后角度服务/工厂返回
【发布时间】:2014-09-07 23:58:33
【问题描述】:

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

我有一个包含所需数据的 .json 文件。我有一个有身份证的人的名单。我想要一个服务或工厂,我可以使用一个参数进行查询,该参数将 http.get 一个我拥有的 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

【问题讨论】:

  • 您是否检查过您的控制台并看到错误。您的代码中似乎存在语法错误。 .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 }); }); }}]);您的过滤器函数中的返回语句已关闭
  • @PSL 这可能是我试图为这个问题做一个最小的可运行代码。它没有抛出错误,只是返回一个空对象

标签: json angularjs q


【解决方案1】:

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

.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 });
      });
}}]);

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

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

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

【讨论】:

  • 蹩脚,这有点像我试图避免的。现在我正在尝试提供两种服务,一种是获取 ajax,另一种是等待 ajax 然后对其进行过滤
  • @charmonkie 什么是跛脚?这就是使用 Promise 的美妙之处...您可以通过更改前一条链上的数据来链接它们...
  • 必须将 then + 过滤器的东西放在控制器中。
  • @charmonkie 是的,您可以将其移至您的服务中,这很好……但我不明白您的说法one to grab the ajax, another to wait for the ajax then filter on it
  • 我在想我可以使用一项服务来检索 json。然后另一个具有 .then 或 .success 函数的服务,控制器将调用第二个函数,该函数将处理成功的内容,因此控制器可以调用 @scope.obj = GetObj(id);
猜你喜欢
  • 2016-07-20
  • 1970-01-01
  • 2017-03-09
  • 2016-07-20
  • 2016-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多