javascript tutorial - [Solved-5 Solutions] Service VS provide VS factory - javascript - java script - javascript array
Problem:
What is the differences between a Service, Provider and Factory in AngularJS ?
Solution 1:
" Hello world " example with factory / service / provider:
Solution 2:
- This is very confusing part for newbie and WE have tried to clarify it in easy words
- AngularJS Service: is used for sharing utility functions with the service reference in the controller. Service is singleton in nature so for one service only one instance is created in the browser and the same reference is used throughout the page.
- In the service, we create function names as property with this object.
- AngularJS Factory: the purpose of Factory is also same as Service however in this case we create a new object and add functions as properties of this object and at the end we return this object.
- AngularJS Provider: the purpose of this is again same however Provider gives the output of it's $get function.
- Defining and using Service, Factory and Provider are explained at
Solution 3:
Visibility of injectables is different for providers than it is for services and factories. If us declare an AngularJS "constant" (for example, myApp.constant('a', 'Robert');)
, uscan inject it into services, factories, and providers.
But if usdeclare an AngularJS "value" (for example., myApp.value('b', {name: 'Jones'});)
, uscan inject it into services and factories, but NOT into the provider-creating function. Us can, however, inject it into the $get function that us define for your provider. This is mentioned in the AngularJS documentation, but it's easy to miss. Us can find it on the %provide page in the sections on the value and constant methods.