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. (eg. Shopping Cart)

 

  • Double Plus Good for sharing a set of functions which don't need any persistent data. (eg. $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?

Services are defined by their constructor function, and operate on

this

 

Factories return an object, and that object can be anything

 

Best practice is generally to use a Service

All Together Now

var application = angular.module('app',[]);
  .controller("MainController", 
    function($scope, MathFactory, CalcService){
      console.log(MathFactory.square(2));
      console.log(CalcService.square(2));
    }
  }

application.service('CalcService', function(){
   this.square = function(a) {
      return a * a;
   }
});

application.factory('MathFactory', function() {
   var factory = {};
   
   factory.square = function(a) {
      return a * a;
   }
   
   return factory;
}); 

Questions?

Creating Angular Services

By LizTheDeveloper

Creating Angular Services

  • 1,467