Creating Angular Services
Services are Great
- Share code, functions, and data across modules
- Gives us flexibility the same way "require" does
- Helps us with the single responsibility principle and separation of concerns
"Service"
A service is a "singleton". A single object shared anywhere it is injected.
"Factory"
Even though they are called Factories, these are still just singletons.
Two Flavors Same Taste
Service
Instance
Controllers
Factory
Instance
Controllers
Why Use One?
- Best when you need to share one copy of data across multiple locations. "Shopping Cart"
- Double Plus Good for sharing a set of functions which don't need any persistent data. "$http"
Make a Service
mainApp.service('CalcService', function(){
this.square = function(a) {
return a * a;
}
});
- Use 'this' keyword to define what will be a public member of the service.
- The 'service constructor' doesn't return anything.
- Essentially, the function is a constructor function, invoked with the new keyword
Make a Factory
mainApp.factory('MathService', function() {
var factory = {};
factory.square = function(a) {
return a * a;
}
return factory;
});
- Instead of acting like a constructor, factories instantiate an object, then return that object.
- This returned object is *STILL A SINGLETON* which will be created once per app, not once per injection.
Why Two?
Frankly, it's unclear to the community why there are two.
Most people have agreed that the best practice is to use factories, because we get slightly more flexibility.
All Together Now
var application = angular.module('app',[]);
.controller("MainController",
function($scope, MathService, CalcService){
console.log(MathService.square(2));
console.log(CalcService.square(2));
}
}
application.service('CalcService', function(){
this.square = function(a) {
return a * a;
}
});
application.factory('MathService', function() {
var factory = {};
factory.square = function(a) {
return a * a;
}
return factory;
});
Questions?
Creating Angular Services
By Tyler Bettilyon
Creating Angular Services
- 1,410