Reputation: 243
I'm working with angular in my application to display a list of news items. When I go to a particular page, I want to display all the information for that one particular news item. I am trying to use $stateParams in my get call to my service, but instead of getting back just the one, I am getting back the whole list of news items.
I should add that the API I am using is just a mock .json file that I am using for testing purposes.
Here is my route where I am using resolve to call my service:
.state('hub.news-detail', {
url: '/news/{id}',
title: 'News',
templateUrl: helper.basepath('news-detail.html'),
resolve: {
getNewsItem: function($stateParams, News){
return News.query({id: $stateParams.id}).$promise;
}
},
controller: 'NewsDetailController'
})
And my service looks like this:
(function() {
'use strict';
angular
.module('hub.news')
.factory('News', News);
News.$inject = ['$resource'];
function News($resource) {
var resource = $resource('/client/server/news.json', {id: '@news_id'}, {
query: {method:'GET', isArray: true},
});
return resource;
}
})();
If I console.log out what I am getting back, I get the entire list of news items:
[Resource, Resource, Resource, Resource, Resource, Resource, Resource, Resource, Resource, $promise: Promise, $resolved: true]
Is there something wrong with my code, or are you unable to filter by ID when working with mock json data?
Upvotes: 1
Views: 830
Reputation: 18875
The problem is with the url you use in the $resource(). I guess the following API returns you an array of all the news, which you can check by simply call it in your browser:
/client/server/news.json
To use the $resource() approach in your service, you need to plug in what id you want to pull from the API. Something like this:
$resource('/client/server/news.json/:id', {id: '@news_id'}
I suggest you read the documentation on $resource here:
Upvotes: 1
Reputation: 24551
When you make this call
$resource('/client/server/news.json', {id: '@news_id'}
angular actually sends GET
request to the server. This looks like the following:
<your server>/client/server/news.json
or
<your server>/client/server/news.json?id=<particular news id>
Now what you do is passing the id, but you don't even include it in the url, it must be e.g. the following:
var resource = $resource('/client/server/news.json/:id', {id: '@news_id'}
and then it will generate the following url:
<your server>/client/server/news.json/<particular news id>
But as long as your JSON is a static file it cannot process the parameters you pass. So it does not matter what you send to the JSON, it will be anyway the same JSON.
Finally, answering your question: no, you cannot do it with a mock JSON.
Upvotes: 1