Reputation: 23
I'm developing my first angularjs application consuming a rest api. I understand that I could use a service to call the rest api.
Let's say I have an api called acme. In acme I could return a list of users and a list of activities.
Should I create one service file, let's say acmeService.js, that returns both the list of users and the list of activities along with any crud activity?
For example:
this.getUsers = function(url){
if (!url) {
url = BASE_URL + '/users';
}
return $http.get(url);
};
// Code for User CRUD
this.getActivities = function(url){
if (!url) {
url = BASE_URL + '/activities';
}
return $http.get(url);
};
// Code for Activity CRUD
Or should I create a service file for each entity along with its Crud operations?
For example:
userAcmeService.js
this.getUsers = function(url){
if (!url) {
url = BASE_URL + '/users';
}
return $http.get(url);
};
// Code for CRUD
activityAcmeService.js
this.getActivities = function(url){
if (!url) {
url = BASE_URL + '/activities';
}
return $http.get(url);
};
// Code for CRUD
I may be looking at this wrong but any guidance is appreciated
Upvotes: 2
Views: 740
Reputation: 66971
You could do either way honestly, I think that's completely up to you! You could just have one big service object with the 2 separated inside.
Also if you have CRUD operations within your REST API, why not try using $resource
? It'll create all the methods for you! get / save / query / remove / delete
As in the example:
app.factory("Post", function($resource) {
return $resource("/api/posts/:id");
});
app.controller("PostIndexCtrl", function($scope, Post) {
// This would "get all"
Post.query(function( data ) {
$scope.posts = data;
});
});
https://docs.angularjs.org/api/ngResource/service/$resource
Note: You have to include the angular-resource.js file before injecting it into a factory/service/etc
Upvotes: 1