I'm writing an AngularJS client application that would interact with a REST server.
To manage the client / server interaction I'm using the $resource abstraction. Actually I'm writing every resource as a separated service and injecting it only in the controllers that are gonna use it.
I've started to develop using the angularjs-seed, so in my separed services.js
file I've got an increasing number of services:
angular.module('testReqService', ['ngResource']).
factory('TestReq', function($resource){
return $resource('http://test-url.com/api/test', {}, {});
});
angular.module('registerService', ['ngResource']).
factory('Register', function($resource){
return $resource('http://test-url.com/api/user/new', {}, {});
});
//More services here...
Everything works fine, but I'm wondering if this is the best approach.
So, is better to write separate services for different REST
requests and inject them only in the controllers that need it, or a better approach is to write a single service with different methods and URL for every request?
In AngularJS, a service is a function, or object, that is available for, and limited to, your AngularJS application. AngularJS has about 30 built-in services. One of them is the $location service.
JavaScript has an extensive user interface that includes sliders and other features. On the other hand, AngularJS is a data-driven framework that's used to create web applications. JavaScript is a powerful and complex programming language. On the other hand, AngularJS is a simple and effective framework.
Each version of Angular has significant benefits, but there is much to gain in being up-to-date with the latest version. Angular is decidedly faster than AngularJS, has a mobile-driven approach, executes better with components, and enables smoother migration from earlier versions.
I prefer the second approach:
var resources = angular.module("myapp.resources", ['ngResource']);
resources.factory('Constants', [
function() {
return {
RESOURCE_URL: "http://www.example.com/rest"
}
}
]);
resources.factory('Rest', ['Constants', '$resource', function(C, $resource) {
return {
Users: $resource(C.RESOURCE_URL + '/users/:id', {
id: '@id',
}, {})
, Posts: $resource(C.RESOURCE_URL + '/posts/:user', {
user: '@'
}, {})
}
}]);
When you have several resources, become very annoying to manage all the dependencies in your controller. That way, all you have to do is inject a single one. It is also, in my opinion, easier to understand when reading the controller:
$scope.user = Rest.Users.get({id: 1});
is more understandable that
$scope.user = Users.get({id: 1});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With