Service vs Factory vs Provider in AngularJS

Loading

In AngularJS, Service, Factory, and Provider are used for dependency injection to create reusable components. They help manage application logic, API calls, and shared data. However, each has distinct differences in how they are implemented and used.

This guide will cover:

  1. What is a Service, Factory, and Provider?
  2. Differences between them
  3. When to use each one
  4. Code examples for better understanding

1. Service in AngularJS

A Service in AngularJS is a singleton object that can hold business logic and state. It is instantiated once and shared across the application.

Key Features:

✔ Uses constructor functions
✔ Returns an instance of the function
✔ Best for objects with methods and properties

Example of Service

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

app.service("MathService", function () {
this.square = function (num) {
return num * num;
};

this.cube = function (num) {
return num * num * num;
};
});

app.controller("MainController", function ($scope, MathService) {
$scope.number = 5;
$scope.squared = MathService.square($scope.number);
$scope.cubed = MathService.cube($scope.number);
});

How it works:

  • The MathService provides reusable methods (square and cube).
  • It is injected into MainController and used directly.

2. Factory in AngularJS

A Factory in AngularJS is a function that returns an object. It allows more flexible logic before returning the final object.

Key Features:

✔ Uses a function that returns an object
✔ Allows additional logic before returning the object
✔ More flexible than a service

Example of Factory

app.factory("MathFactory", function () {
var mathOperations = {};

mathOperations.square = function (num) {
return num * num;
};

mathOperations.cube = function (num) {
return num * num * num;
};

return mathOperations;
});

app.controller("MainController", function ($scope, MathFactory) {
$scope.number = 5;
$scope.squared = MathFactory.square($scope.number);
$scope.cubed = MathFactory.cube($scope.number);
});

How it works:

  • The MathFactory creates an object (mathOperations) and returns it.
  • The controller receives the returned object and uses its methods.

🔹 Key Difference: Factory allows you to define private variables and logic inside the function before returning the object.


3. Provider in AngularJS

A Provider is the most powerful and flexible way to create services. It allows configuration before the service is used.

Key Features:

✔ Uses a .provider method
✔ Provides a .config() function for early customization
✔ Used when services need configuration before being injected

Example of Provider

app.provider("MathProvider", function () {
var precision = 2;

this.setPrecision = function (p) {
precision = p;
};

this.$get = function () {
return {
square: function (num) {
return Number((num * num).toFixed(precision));
},
cube: function (num) {
return Number((num * num * num).toFixed(precision));
}
};
};
});

// Configure Provider before use
app.config(function (MathProviderProvider) {
MathProviderProvider.setPrecision(4);
});

app.controller("MainController", function ($scope, MathProvider) {
$scope.number = 5;
$scope.squared = MathProvider.square($scope.number);
$scope.cubed = MathProvider.cube($scope.number);
});

How it works:

  • The Provider allows setting precision using setPrecision() in the .config() phase.
  • MathProvider.$get() provides the final service.

🔹 Key Difference: Only Provider can be configured before the app runs.


4. Key Differences: Service vs Factory vs Provider

FeatureServiceFactoryProvider
ReturnsInstance of functionObject$get() function
UsageGood for objects with methodsGood for object creation logicBest for configurable services
InstantiationUses new keywordFunction returns an objectUses $get()
Configurable in config()? No No Yes
Complexity Simple Moderate Complex

5. When to Use Service, Factory, or Provider?

Use Service when:

  • You need an object with methods.
  • No configuration is needed.
  • Example: Business logic functions, utility methods.

Use Factory when:

  • You need to control what gets returned.
  • You need to create and return objects dynamically.
  • Example: API calls, caching, flexible object creation.

Use Provider when:

  • You need to configure a service before it is used.
  • Example: Setting API URLs, configuring authentication tokens.

Leave a Reply

Your email address will not be published. Required fields are marked *