Open In App

Difference between factory, service & provider ?

Last Updated : 10 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In AngularJS, there are three main types of components: factories, services, and providers. Each of these components serves a different purpose and has its own characteristics.

Factory: Factories are functions that return objects or functions. They are created using the factory function, which takes a function as an argument and returns a factory function. Factories can be injected into other components as dependencies, and are instantiated at runtime when they are injected. They cannot be configured using the config function.

Syntax:

// Create the factory
   .factory("myFactory", function () {
     return {
      ....
       }
     }
   })

Service: Services are objects that are created using the service function, which takes a function as an argument and returns a service object. Services can be injected into other components as dependencies, and are instantiated at runtime when they are injected. They cannot be configured using the config function.

Syntax:

// Create the service
   .service("myService", function () {
   .....
     }
   })

Provider: Providers are objects that are created using the provider function, which takes a function as an argument and returns a factory function that can be used to create the service. Providers can be injected into other components as dependencies, and are instantiated when their $get method is called. This typically occurs when the provider is injected into a component for the first time. Providers can be configured using the config function, which is called during the configuration phase of an AngularJS application. This allows providers to be configured before the application has been bootstrapped.

Syntax:

// Create the provider
   .provider("myProvider", function () {
     this.$get = function () {
       return {
         ....
         }
       }
     }

Approach 1: In this approach, the code creates an AngularJS module “myModule” and three different types of AngularJS components: a factory, a service, and a provider. Each of these components is used to create an object with a single method “sayHello” that returns a string. The code then creates a controller “MyController” that is associated with the “myModule” module. The controller uses the $scope object to bind the return values of the “sayHello” methods of the factory, service, and provider to variables “factoryMessage”, “serviceMessage”, and “providerMessage” respectively.

Example: In this example, we have displayed the simple messages from the factory, service & provider in AngularJS.

HTML




<!DOCTYPE html>
<html ng-app="myModule">
  
<head>
    <script src=
    </script>
    <style>
        h1 {
            color: green;
        }
    </style>
</head>
  
<body ng-controller="MyController">
    <center>
        <h1> GeeksforGeeks</h1>
        <h3>
            Difference between factory, service & provider ?
        </h3>
        <p>Factory: {{factoryMessage}}</p>
        <p>Service: {{serviceMessage}}</p>
        <p>Provider: {{providerMessage}}</p>
    </center>
  
    <script>
        // Create the module
        angular.module("myModule", [])
  
            // Create the factory
            .factory("myFactory", function () {
                return {
                    sayHello: function () {
                        return "Hello from the factory!";
                    }
                }
            })
  
            // Create the service
            .service("myService", function () {
                this.sayHello = function () {
                    return "Hello from the service!";
                }
            })
  
            // Create the provider
            .provider("myProvider", function () {
                this.$get = function () {
                    return {
                        sayHello: function () {
                            return "Hello from the provider!";
                        }
                    }
                }
            });
  
        // Create the controller
        angular.module("myModule")
            .controller("MyController", MyController);
  
        function MyController($scope, myFactory, myService, myProvider) {
            $scope.factoryMessage = myFactory.sayHello();
            $scope.serviceMessage = myService.sayHello();
            $scope.providerMessage = myProvider.sayHello();
        }
    </script>
</body>
  
</html>


Output:

 

Approach 2: In this approach, we have defined a factory service TodoFactory and a provider service TodoProvider for maintaining a to-do list. Both the factory and provider have an addTodo() method which adds a new todo to the list and the getTodos() method which returns the list of todo.

Example: This example illustrates the Todo list using Factory and Provider in AngularJS.

HTML




<!DOCTYPE html>
<html ng-app="todoApp">
  
<head>
    <script src=
    </script>
    <style>
        h1 {
            color: green
        }
  
        button {
            color: white;
            background-color: black;
            height: 50px;
            width: 130px;
            padding: 3px;
            margin: 5px;
            border-radius: 5px;
        }
  
        input {
            width: 200px;
            padding: 5px 15px;
            margin: 5px 0;
            box-sizing: border-box;
            border: 2px solid #ccc;
            border-radius: 4px;
        }
    </style>
    <script>
        var app = angular.module("todoApp", []);
  
        // Factory
        app.factory("TodoFactory", function () {
            var factory = {};
            factory.todoList = [];
  
            factory.addTodo = function (todo) {
                factory.todoList.push(todo);
            };
  
            factory.getTodos = function () {
                return factory.todoList;
            };
  
            return factory;
        });
  
        // Provider
        app.provider("TodoProvider", function () {
            var provider = {};
            provider.todoList = [];
  
            provider.$get = function () {
                var service = {};
  
                service.addTodo = function (todo) {
                    provider.todoList.push(todo);
                };
  
                service.getTodos = function () {
                    return provider.todoList;
                };
  
                return service;
            };
  
            return provider;
        });
  
        // Controller
        app.controller("TodoController", 
            function ($scope, TodoFactory, TodoProvider) {
            $scope.addTodoFactory = function () {
                TodoFactory.addTodo($scope.newTodo);
                $scope.factoryTodoList = TodoFactory.getTodos();
            };
  
            $scope.addTodoProvider = function () {
                TodoProvider.addTodo($scope.newTodo);
                $scope.providerTodoList = TodoProvider.getTodos();
            };
        });
    </script>
</head>
  
<body ng-controller="TodoController">
    <center>
        <h1> GeeksforGeeks</h1>
        <h3>
            Difference between factory, service & provider ? 
        </h3>
        <input type="text" 
               ng-model="newTodo" 
               placeholder="Enter new Todo">
        <button ng-click="addTodoFactory()">
            Add Todo using Factory
        </button>
        <button ng-click="addTodoProvider()">
            Add Todo using Provider
        </button>
    </center>
    <div>
        <h3>Todo List using Factory</h3>
        <ul>
            <li ng-repeat="todo in factoryTodoList">
                {{todo}}
            </li>
        </ul>
    </div>
    <div>
        <h3>Todo List using Provider</h3>
        <ul>
            <li ng-repeat="todo in providerTodoList">
                {{todo}}
            </li>
        </ul>
    </div>
</body>
  
</html>


Output:

 

Difference between the factory, service & provider in AngularJS:

Component

Creation

Injection

Configuration

Instantiation

Factory Created using the factory function, which takes a function as an argument and returns a factory function. No No Can be configured using the config function.
Service Created using the service function, which takes a function as an argument and returns a service object. Yes No Can be configured using the config function.
Provider Created using the provider function, which takes a function as an argument and returns a factory function that can be used to create the service. Yes Can be configured using the config function. Instantiated when the $get method is called, typically when the provider is injected into a component for the first time.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads