我的 JSON 数据如下所示,包含在名为“parks.json”的文件中:
{
"description": "Farnborough features a good amount of green space and is indeed surrounded by plenty more. Our Parks section aims to tell you, not only where they all are but a little bit about the history behind them and the people who look after them today.",
"id": "parks",
"name": "Parks",
"locations": [
{
"name": "Queen Elizabeth Park",
"lat": 51.29692,
"lng": -0.76080000000000003,
"synopsis": "Once part of Windsor Great Park"
},
{
...
}
]
}
以下 $resource 查询将检索上述数据片段:
return $resource('locations/:categoryId.json', {}, {
query: {method:'GET', params:{categoryId:'categories'}, isArray:true}
});
传入的 categoryId 是“parks”,因此上面的代码将检索我的整个 Parks.json 文件并将其加载到一个对象中。这很好,但是,我只想将其中的一部分提取到数组或对象中。
我的问题是如何调整以上内容以仅提取位置?我对纬度和经度值特别感兴趣。我已经让其他各种事情正常工作,需要确定这种行动,因为我不太熟悉如何做到这一点。
干杯!
最佳答案
一些事情:
- 这可能不是
$resource
的最佳用途。$http
在这种情况下更可取,因为您并不是真正在处理 RESTful Web 服务。您显然是在处理 .json 文件上的GET
。使用$resource
将实例化一堆您不需要且无法使用的额外功能和开销。 - 过滤返回结果的最佳位置是服务器。我知道你不能用 .json 文件真正做到这一点,但值得一提。
- 这实际上不是 $resource 甚至 Angular 的问题,而是 JavaScript 的问题,您要做的是从数组中获取对象的子集。
综上所述...如果您必须使用 $resource 执行此操作,您可以执行类似于以下伪代码的操作:
// a factory to create your Park resource service.
app.factory('Park', ['ngResource', function($resource) {
//your Park resource constructor.
var Park = $resource('locations/:categoryId.json', {}, {
query: {method:'GET', params:{categoryId:'categories'}, isArray:true}
});
//a "static" function on Park to filter results.
Park.filter = function(parks, predicate) {
var results = [];
for(var i = 0; i < parks.length; i++) {
var park = parks[i];
if(predicate(park)) {
results.push(angular.copy(park));
}
}
return results;
};
//return the constructor
return Park;
}]);
// a controller example to consume your service.
app.controller('MainCtrl', function($scope, Park) {
// get all parks in category 123
var allParks = Park.query({categoryId: 123});
// filter the parks down to the ones named "Hooterville Park"
$scope.parks = Park.filter(allParks, function(park) {
return park.name === 'Hooterville Park';
});
});
问题是,$resource 可以像这样与 RESTful 资源一起使用:
// create a basic resource.
var Foo = $resource('/Foo/:id');
// get and update one item.
var foo = Foo.get(123, function() {
foo.name = 'Test';
foo.email = 'blah@sample.com';
foo.$save();
});
// create a new item.
var foo2 = new Foo();
foo2.name = 'New guy';
foo2.email = 'new@guy.com';
foo.$save();
// get and update a bunch of items.
var foos = Foo.query();
for(var i = 0; i < foos.length; i++) {
var fooItem = foos[i];
fooItem.name = 'Foo ' + i;
fooItem.$save();
}
所以除非你打算做那些事情,否则我会说继续使用 $http。
关于javascript - 我希望从 Angular 资源加载数据子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13483738/