In any application sometimes you need to share some code or common functionalities among the components of the application. One way to do it is using a services pattern. In AngularJs Applications there are three ways to create them: services and factories.
Services vs Factories in Angularjs
The first thing to know is the difference between these kind of objects. In this post https://tylermcginnis.com/angularjs-factory-vs-service-vs-provider/ the author gives the definitions of each kind of components and illustrate them with clear examples.
Factories
When you create a factory, you define an object with its properties and methods and return it directly. Then this same object will be used in the controllers where it is injected in the usual ways.
app.factory("aFactory", function () {
var property = "";
method = function () {
return property;
};
return { method: getProperty };
});
Services
When a service is instantiated it's called the defining function with the new keyword so the object returned is a new instance of the object created with the function.
app.service("aService", function () {
var property = "";
this.getProperty = function () {
return property;
};
});
Providers
The providers are the only kind of service that you can pass to the application config function so if you have to use or configure a service in the moment you are configuring the app you need to create it as a provider. The object returned in the inner $get method will be the available when you use it in your controllers.
app.provider("aProvider", function () {
this.property = "";
this.propertyWhenConfig = "";
//Only the properties on the object returned from $get are available in the controller.
this.$get = function () {
var that = this;
return {
getProperty: function () {
return that.property;
},
getPropertyWhenConfig: that.propertyWhenConfig,
};
};
});
Services and Factories in the App
These are the services and factories</a> created in the development of the Strikethru App with Ionic.
Factories
Todos
Recover todos items from a list, and add, modify and remove as move items from list to list. These lists are the Livelist, the Dump or each one of the lists for each Vault category.
Vault
Manage Vault category, list, add, modify and delete.
Auth
Authenticatin methods like author or logout and getCurrentUser
Services
Calendar
Create Events to the device calendar app from the information of the item selected.
ChoosePriorityPopup
A popup service that allows you to choose a value for the priority. Using this as a service allows you to reuse the same service and not create a new component each time you need to select it.
VaultPopup
Pop up to choose Vault Category
Confirm
modal popup to confirm action
CurrentListService
From the Url or $state, it gets the current list. Useful to known from which list are you moving an item to
Setup
Service to load and check user configuration like the values 1-3-5 1-9 or kind of setup