Angular Factory vs. Service vs. Provider

To promote code reusability Angular supports the ability to inject reusable services. There are three main ways to inject services into angular controllers, all of which are singleton objects and is the same instances being injected every time.

Factory

When a factory instance is created properties/methods assigned to the object, and the object is injected into the angular controller. The following code shows how a factory instance is defined:

angularApp.factory('factory_name', () =>{
var instance = {};
instance.prop='';
return instance;
});

Service

When a service is created ‘new’ syntax is used. The properties/methods are assigned to this, and ‘this’ is returned/injected instance.
The following code shows how a factory instance is defined:

angularApp.service('service_name', () =>{
/*when service is declared 'new' is used meaning in the background*/
var obj = Object.create(...);
this = obj;
this.prop='';
return this;
});

Provider

This is the only angular type can be injected into the angularApp.config(). Use this type when you need a service to alter service(provider) in angularApp.config() before the provider instance is injected to Angular controllers.

//Example:
angularApp.provider('providerName', () =>{ ... });
angularApp.config((providerInstance) => { ... });
angularApp.controller('controllerName', (providerInstance) =>{ ... })

Source

Leave a Reply

Your email address will not be published. Required fields are marked *