Difference between Services and Factories

Loading

In AngularJS, both Services and Factories are used to create reusable components that manage business logic and share data between controllers. However, there are key differences in how they are implemented and instantiated.

This guide covers:

What are Services and Factories?
Key differences between Services and Factories
When to use which?
Code examples for better understanding


1. What is a Service in AngularJS?

  • A Service is a singleton object that is instantiated using the service method.
  • It is a constructor function that gets instantiated with the new keyword.
  • Properties and methods are attached to this inside the constructor.
  • It provides a cleaner syntax for object-oriented programming.

Syntax

app.service("MyService", function() {
this.message = "Hello from Service!";

this.getMessage = function() {
return this.message;
};
});

How to Use the Service?

app.controller("MyController", function($scope, MyService) {
$scope.greeting = MyService.getMessage();
});

Key Points

✔️ Uses this keyword to define methods.
✔️ Instantiated with new MyService().
✔️ Best suited for Class-based objects.


2. What is a Factory in AngularJS?

  • A Factory is a function that returns an object.
  • It allows more flexibility compared to a Service.
  • The returned object contains methods and properties that can be used across controllers.

Syntax

app.factory("MyFactory", function() {
var factory = {};
factory.message = "Hello from Factory!";

factory.getMessage = function() {
return factory.message;
};

return factory;
});

How to Use the Factory?

app.controller("MyController", function($scope, MyFactory) {
$scope.greeting = MyFactory.getMessage();
});

Key Points

✔️ Returns an object explicitly.
✔️ Does not use this.
✔️ Best suited for creating custom objects or logic-based processing.


3. Key Differences Between Services and Factories

FeatureServiceFactory
DefinitionA constructor function that gets instantiated with newA function that returns an object
SyntaxUses this keyword to define methodsCreates an object, adds properties to it, and returns it
Instance CreationAngularJS automatically instantiates it with newManually creates and returns an object
FlexibilityLess flexible as it must use thisMore flexible since it allows custom object creation
PerformanceSlightly better as it avoids unnecessary object creationCan have performance overhead if creating multiple instances manually
Use CaseBest for defining reusable services with a fixed structureBest for creating objects with custom logic and flexibility

4. Which One Should You Use?

Use a Service when:

  • You need a single instance with object-oriented programming.
  • You want a clean and simple syntax with this.
  • You are working with stateful services (like authentication, user sessions).

Use a Factory when:

  • You need more control over object creation.
  • You want to return different objects based on conditions.
  • You need lightweight, flexible, and reusable services.

5. Example: Authentication Service vs Factory

Using a Service

app.service("AuthService", function() {
this.isAuthenticated = false;

this.login = function() {
this.isAuthenticated = true;
};

this.logout = function() {
this.isAuthenticated = false;
};

this.checkStatus = function() {
return this.isAuthenticated;
};
});

Using a Factory

app.factory("AuthFactory", function() {
var auth = { isAuthenticated: false };

auth.login = function() {
auth.isAuthenticated = true;
};

auth.logout = function() {
auth.isAuthenticated = false;
};

auth.checkStatus = function() {
return auth.isAuthenticated;
};

return auth;
});

Which One to Use?

  • Use AuthService if you want an OOP approach with an instantiable service.
  • Use AuthFactory if you want flexibility and more control over object manipulation.

Leave a Reply

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