【发布时间】: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 这可能是我试图为这个问题做一个最小的可运行代码。它没有抛出错误,只是返回一个空对象