Reputation: 12445
Just starting out on AngularJS & js (being a backend developer) and this is the first Javascript MVC framework which I have ever worked on so please go easy...
I have a restful json API which I would like to consume using AngularJS.
In order to implement this, I have created two factories, one singular for when a controller needs to query the factory with an id, and a plural factory for when id is not required.
e.g. below:
Controller to list all products:
app.controller('ProductController', function($scope, ProductsFactory) {
$scope.products = [];
init();
function init()
{
$scope.products = ProductsFactory.query();
}
});
Factories:
app.factory('ProductsFactory', function($resource) {
return $resource('/xxx/xxx/xxx/api/v1/product', {}, {
query: { method: 'GET', isArray: true },
create: { method: 'POST' }
});
});
app.factory('ProductFactory', function($resource) {
return $resource('/xxx/xxx/xxx/api/v1/product/:id', {}, {
show: { method: 'GET' },
update: { method: 'PUT', params: { id: '@id' } },
delete: { method: 'DELETE', params: { id: '@id' } }
});
});
Question 1: Am I implementing the resource factory correctly?
Question 2: Is there a way of just using one factory for Products? e.g. allowing the factory to decide that id is not necessary for query
and create
, but is required for show
, update
and delete
methods?
Upvotes: 0
Views: 725
Reputation: 2223
Yes, you can use just 1 factory :
app.factory('ProductFactory', function($resource) {
return $resource('/xxx/xxx/xxx/api/v1/product/:id', { id : '@id'}, {
update: { method: 'PUT' },
});
});
You don't need to specify the 'params' object to every requests. Defining it for the $resource is often enough (but if you want to overwrite it of course you can use it).
Notice that you don't need to define the CRUD methods since the $resource already implements them (as stated in the doc : http://docs.angularjs.or/api/ngResource.$resource).
At the moment, you just need to define a custom method update if you want to use "PUT" but a pull request is opened (https://github.com/angular/angular.js/pull/3416) and I hope we can expect to see it implemented soon.
Upvotes: 1