Service vs Factory vs Provider
Services in AngularJS are used to organize the code and share it anywhere in the application. AngularJS has many built-in services to perform specific tasks. These built-in services starts with a ‘$’.
Eg: $location, $log, $route, $scope, etc.
Apart from these inbuilt services, it is possible to create a user-defined service. This can be done with the help of Service, Factory and Provider.
If a controllers / directives / service have to use a services, then those services are to be added as dependencies to them.
Service
Service is a Singleton object i.e.; a single-instance object that provides additional functionality to the controller. They can be simply referred as JavaScript functions that perform specific tasks to support the app’s functionality.
Service invokes ‘new’ on the constructor method passed to it.
Services add properties to ‘this’ and returns the ‘this’ result.
Syntax:
myApp.service( ‘ServiceName’ , function(){ … return …; })
Factory
Factory is referred as a function that is responsible to create certain values.
It invokes a function passed to it.
Factory adds properties and returns the object as a result.
Syntax:
myApp.factory( ‘FactoryName’ , function(){ … return …; })
Providers
Providers combine Factory and Services
Providers are the only service that can be passed into the config(). i.e.; Providers are used by the AngularJS to create services, factory, etc internally during the config phase.