Tuesday 3 May 2016

AngularJs Service, Factories and Providers

 Service in AngularJS

AngularJs Service, Factories and providers are all injectable types.
An AngularJs service encapsulates specific business logic & exposes an API to be used by other components to invoke this logic.

e.g. $timeout service executes function after specifies interval. $http service encapsulates the logic required to interact with REST backbends.

AngularJS service is always Singleton.

Service is registered using service function of angular.module().
The Second argument to service() is a constructor function to inject the service.


e.g.

       var myApp = angular.module('myApp', []);

       //service style, probably the simplest one
       myApp.service('helloWorldFromService'function() {
           this.sayHello = function() {
               return "Hello, World!"
           };
       });


Factory method in AngularJS

Factory method is same as service method but it is more robust than service and you can expose only that logic which you want to expose.

       //factory style, more involved but more sophisticated
       myApp.factory('helloWorldFromFactory'function() {
           return {
               sayHello: function() {
                   return "Hello, World!"
               }
           };
       });

Difference between factory and service is factory exposes logic on return type but in service you will access logic directly by service name and function name.

Providers in AngularJS

A provider is most configurable and verbose version of service because its based on prior setting and logic.
e.g. the built in $route service may behave differently based on Mode(Html mode or hashbag mode) you can configured in $route.Provider

       //provider style, full blown, configurable version    
       myApp.provider('helloWorld'function() {

           this.name = 'Default';

           this.$get = function() {
               var name = this.name;
               return {
                   sayHello: function() {
                       return "Hello, " + name + "!"
                   }
               }
           };

           this.setName = function(name) {
               this.name = name;
           };
       });

       //we can configure a provider!           
       myApp.config(function(helloWorldProvider){
           helloWorldProvider.setName('World');
       });


No comments:

Post a Comment