Monday 17 April 2017

AngularJS : Service vs factory vs provider

Introduction
AngularJS Service, Factory or Provider all are used for the same purpose of creating utility function that can be used throughout the page with inject-able object. However, the way it is created and the way it is used are different. Here we'll try to understand them clearly.

AngularJS Service
The services are singleton objects or functions that carry out specific tasks. It holds some business logic functions.These functions can be called from anywhere; Controllers, Directive, Filters etc.
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. In other words,
with the factory you actually create an object inside of the factory and return it.  

AngularJS Provider
The purpose of this is again same however Provider gives the output of it's $get function.

One more important link is here
Now let's try to understand Service, Factory and Provider by creating and using them.
Creating Service, Factory and Provider

In below code snippet, we shall see how to create a Service, Factory and a Provider. First, we have created a module. 

Next is the Service creation where we have created a service using .service method. Notice that in the service both functions "Hello" and "Sum" have been created on "this" object.

Then we have created a factory using .factory method. Here, we have created both functions "Hello" and "Sum" on the new object "factoryObject" created and then we are returning that object at the end of the factory method.

In the last, we have created a provider using .provider method in which we are returning an object having two functions "Hello" and "Sum" to the $get function.


var app = angular.module("app", []);

    // create utility function with service
    app.service("myService", function () {
        // here we expose the function on this object
        this.Hello = function () {
            return "Hello";
        };
        this.Sum = function (a, b) {
            return a + b;
        };
    });

    // create utility function with factory
    app.factory("myFactory", function () {
        // here we return the object
        var factoryObject = {};
        factoryObject.Hello = function () {
            return "Hello";
        }
        factoryObject.Sum = function (a, b) {
            return a + b;
        }
        return factoryObject;
    });

    // create utlity function with provider
    app.provider("myProvider", function () {
        this.$get = function () {
            return {
                Hello: function () {
                    return "Hello";
                },
                Sum: function (a, b) {
                    return a + b;
                }
            };
        };
    });

Notice that despite that all three have the same functions "Hello" and "Sum" having same functionality but the way of declaration is different. This is the major difference between Service, Factory and Provider.
Using Service, Factory and Provider

To use them simply inject those into the controller definition and start using those reference to call functions "Hello" and "Sum" defined in them.

Below code snippet is pretty simple. We are simply calling "Hello" and "Sum" functions defined on respective Service, Factory and Provider reference objects.

app.controller("myController", function ($scope, myService, myFactory, myProvider) {
        // service function call
        $scope.ServiceOutput = "Look for service output here.";
        $scope.HelloService = function () {
            $scope.ServiceOutput = myService.Hello();
        };
        $scope.SumService = function () {
            $scope.ServiceOutput = "The sum is : " + myService.Sum(2, 5);
        };

        // factory function call
        $scope.FactoryOutput = "Look for factory output here.";
        $scope.HelloFactory = function () {
            $scope.FactoryOutput = myFactory.Hello();
        };
        $scope.SumFactory = function () {
            $scope.FactoryOutput = "The sum is : " + myFactory.Sum(22, 5);
        };

        // provider function call
        $scope.ProviderOutput = "Look for factory output here.";
        $scope.HelloProvider = function () {
            $scope.ProviderOutput = myProvider.Hello();
        };
        $scope.SumProvider = function () {
            $scope.ProviderOutput = "The sum is : " + myProvider.Sum(22, 52);
        };
    });

Calling functions defined in Service, Factory and Providers

The HTML code looks like below. Where we have three separate sections each for Service, Factory and Provider. On click respective buttons, functions defined in the controller $scope is being called and the output appears on the page.

<div ng-app="app" ng-controller="myController">
    <h3>Using Service</h3>
    <button ng-click="HelloService()">Hello Service</button>
    <button ng-click="SumService()">Sum Service</button>
    <div ng-bind="ServiceOutput"></div>


    <h3>Using Factory</h3>
    <button ng-click="HelloFactory()">Hello Factory</button>
    <button ng-click="SumFactory()">Sum Factory</button>
    <div ng-bind="FactoryOutput"></div>

    <h3>Using Provider</h3>
    <button ng-click="HelloProvider()">Hello Service</button>
    <button ng-click="SumProvider()">Sum Service</button>
    <div ng-bind="ProviderOutput"></div>
</div>

Conclusion
Broadly there is no difference in terms of output/functionality between Service, Factory and Provider however the difference comes when we try to create them. All three have different way of creation and function implementations.

live working code, click here.

1 comment:

  1. Hi Buddie,


    I love all the posts, I really enjoyed.
    I would like more information about this, because it is very nice., Thanks for sharing.


    i am new in angular 2 and i am using angular 2 with mvc5.
    my problem is that when i go from one view to another view then second view i am not able to load other component.

    For Ex.

    We make a index view and create a home.component.ts and this file load in app.component.ts file and we load app.component.ts from index view. it is working,
    but we go another view from index then in this view we want to load another component except app.component then other component is not loading.

    But great job man, do keep posted with the new updates.


    Regards,

    ReplyDelete

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives