This topic concerns a problem that I faced in these days, that was the building of an Angularjs service to consume Web API’s, witch in my case were implemented with OData protocol.
The start point are some Web API’s, one for every entity of the project, that they responds to a specific url, for example:
I wouldn’t want to implement a service for every single Web API that do the same operations, so the idea is implement a generic javascript class with the basic methods and a factory that generates instances of this class; every module will have an own instance with some custom options, such as the service url.
So what I want to do are two things, a generic class that implements commons methods for CRUD operations and then a factory that generates instances of this service.
Generic service
Angularjs has several provider that we can use to instantiate services; the provider is the lower level and is use usually to configure reusable services that can be used in different applications.
Factory and services are syntactic sugar on top of a provider, and allow us to define singleton services in our application; the last two are constant and value that they provides values.
One of the main debates on Angularjs is when we use a factory or a service.
The main difference from these is that in the first one we needs to return an instance of the service in this way:
(function (window, angular) { 'use-strict' angular.module('odataModule', []) .factory('odataService', [function() { returns { ..... } }]); })(window, window.angular)
In the second one, we don’t need to do this, the angular service deal with object instantiation:
(function (window, angular) { 'use-strict' angular.module('odataModule', []) .service('odataService', [function() { ..... }]); })(window, window.angular)
What I want to implement is a javacript class that will have these properties/methods:
- A url property, the Web API reference
- An entityClass property, is the the javascript object that represents the entity to be managed
- A isNew property, that allow the service to understand that the object need to be added (post) or saved (patch)
- A getEntities method that retrieves the list of the entities
- A createEntity method that returns a instance of a new entity
- A getEntity method to retrieves a single entity
- A saveEntity method that deal with the post/patch of the entity
- And finally a method deleteEntity
An angular service help in this work by letting me write cleaner code that factory; a concrete implementation is:
(function (window, angular) { 'use-strict' angular.module('odataModule', []) .constant('blogsUrl', '/odata/Blogs') .constant('postsUrl', '/odata/Posts') .service('odataService', ['$http', function($http) { function Instance(url, entityObject) { this.isNew = false; this.url = url; this.entityClass = entityObject; } Instance.prototype.getEntities = function () { return $http.get(this.url); } Instance.prototype.createEntity = function() { this.isNew = true; return angular.copy(this.entityClass); } Instance.prototype.getEntity = function (id) { return $http.get(this.url + '(guid\'' + id + '\')'); } Instance.prototype.saveEntity = function (entity) { if (this.isNew) { this.isNew = false; return $http.post(this.url, entity); } else return $http.patch(this.url + '(guid\'' + entity.Id + '\')', entity); } Instance.prototype.deleteEntity = function (entity) { return $http.delete(this.url + '(guid\'' + entity.Id + '\')'); } this.GetInstance = function(url, entityObject) { return new Instance(url, entityObject); }; }]); })(window, window.angular)
The Instance class is the implementation of the common methods that we needed.
The last row is the main difference from a factory; in a service, the container function is a javascript function with a constructor and the service returns an instance of it, so I can define a method GetInstance that will returns an instance of my custom class.
If I had used a factory, the last rows would be the following:
return { GetInstance: function(url, entityObject) { return new Instance(url, entityObject); }
Much better the implementation with the service.
Factories of the entities
Now I need to define a specific factory for every entity:
(function (window, angular) { 'use-scrict'; angular.module('blogsModule', ['ui.router', 'odataModule']) .factory('blogsFactory', ['odataService', 'blogsUrl', function (odataService, blogsUrl) { var blogEntity = { Name: '', Url: '' }; return odataService.GetInstance(blogsUrl, blogEntity); }]) })(window, window.angular)
So far so good, I have an instance of the service with specific parameters, and now I can use the factory for crud operations in my controller:
(function (window, angular) { 'use-scrict'; angular.module('blogsModule', ['ui.router', 'odataModule']) .... .controller('blogsController', ['$scope', '$state', 'blogsFactory', function ($scope, $state, blogsFactory) { $scope.Title = 'Blogs'; blogsFactory.getEntities().then(function (result) { $scope.blogs = result.data.value; }); $scope.create = function() { $state.go('main.blog', { id: null }); }; $scope.edit = function (blog) { $state.go('main.blog', { id: blog.Id }); }; }]) .controller('blogController', ['$scope', '$state', '$stateParams', 'odataService', function ($scope, $state, $stateParams, odataService) { $scope.Title = 'Blog'; var service = new odataService.GetInstance('/odata/Blogs', { Name: '', Url: '' }); $scope.save = function () { service.saveEntity($scope.blog).then(function () { $state.go('main.blogs'); }); }; $scope.delete = function() { service.deleteEntity($scope.blog).then(function () { $state.go('main.blogs'); }); }; $scope.close = function() { $state.go('main.blogs'); }; if ($stateParams.id === '') $scope.blog = service.createEntity(); else { odataService.getEntity($stateParams.id).then(function (result) { $scope.blog = result.data; }); } }]); })(window, window.angular)
With few lines of code I have managed the crud operations.
In my case the odata module can be improved with checks about the entity validations, by using the $metadata informations returned by the odata services and I can retrieve also the entity fields without passing those as parameters, but, anyway, this is a good starting point.