factory
provider
coding
service
angularjs

AngularJS: Service vs provider vs factory

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

In AngularJS, service, factory, and provider are all ways to create and share reusable components. They are part of the dependency injection system and help manage logic, state, or reusable functionality in your app. However, they differ in how they are created and instantiated.


1. Service

A service is a constructor function instantiated using the new keyword. It is simpler and used when you need an object with methods and properties.

Key Characteristics:

  • AngularJS uses the new keyword to instantiate the service.
  • You attach properties and methods to this.
  • Returns a singleton instance of the service.

Syntax:

javascript
1app.service('myService', function() {
2    this.sayHello = function(name) {
3        return "Hello, " + name;
4    };
5});

Usage:

javascript
app.controller('myCtrl', function(myService) {
    console.log(myService.sayHello("AngularJS")); // Output: Hello, AngularJS
});

How It Works:

  • AngularJS internally does:
javascript
  var instance = new MyService();

2. Factory

A factory is a function that returns an object. It allows you to create and configure the object before returning it.

Key Characteristics:

  • It returns an object explicitly.
  • Allows you to construct and customize the object before returning it.
  • More flexible than service.

Syntax:

javascript
1app.factory('myFactory', function() {
2    var service = {};
3
4    service.sayHello = function(name) {
5        return "Hello, " + name;
6    };
7
8    return service; // Explicitly return an object
9});

Usage:

javascript
app.controller('myCtrl', function(myFactory) {
    console.log(myFactory.sayHello("AngularJS")); // Output: Hello, AngularJS
});

How It Works:

  • The factory function returns the object that will be used as the service instance.

3. Provider

A provider is the most powerful and flexible option. It is used to configure services during the config phase. The provider itself has a .$get method, which returns the service.

Key Characteristics:

  • A provider must implement a $get method.
  • Used when you need to configure a service before it is instantiated.
  • Only option available during the config phase.

Syntax:

javascript
1app.provider('myProvider', function() {
2    var greeting = "Hello";
3
4    this.setGreeting = function(newGreeting) {
5        greeting = newGreeting;
6    };
7
8    this.$get = function() {
9        return {
10            sayHello: function(name) {
11                return greeting + ", " + name;
12            }
13        };
14    };
15});

Usage:

You can configure a provider in the config block.

javascript
1app.config(function(myProviderProvider) {
2    myProviderProvider.setGreeting("Hi");
3});
4
5app.controller('myCtrl', function(myProvider) {
6    console.log(myProvider.sayHello("AngularJS")); // Output: Hi, AngularJS
7});

How It Works:

  • You use provider when you need to configure the service before it becomes available.

Comparison Table

FeatureServiceFactoryProvider
What it ReturnsAn instance of the function.An object returned by the factory.Configurable object via $get method.
InstantiationUses new to instantiate.Returns an object explicitly.Uses $get to return the instance.
ConfigurableNo.No.Yes, in the config phase.
When to UseFor simpler logic or methods.When you need to construct an object.When you need pre-instantiation config.
Syntax ComplexitySimpleFlexibleMost flexible, but complex.

When to Use Which?

  • Service: Use when you need a simple object or methods attached to this.
  • Factory: Use when you need more flexibility and control over object creation.
  • Provider: Use when you need to configure the service during the config phase.

Example Summary

Here’s a simple comparison using the same functionality implemented in all three:

Service:

javascript
1app.service('greetService', function() {
2    this.sayHello = function(name) {
3        return "Hello, " + name;
4    };
5});

Factory:

javascript
1app.factory('greetFactory', function() {
2    return {
3        sayHello: function(name) {
4            return "Hello, " + name;
5        }
6    };
7});

Provider:

javascript
1app.provider('greetProvider', function() {
2    this.$get = function() {
3        return {
4            sayHello: function(name) {
5                return "Hello, " + name;
6            }
7        };
8    };
9});

All three can be injected and used in controllers, but providers offer more flexibility through configuration.


Conclusion

  • Use service for simple and straightforward logic.
  • Use factory when you need more control or to return a complex object.
  • Use provider when you need configuration before service instantiation.

Understanding these differences helps you choose the right approach for your AngularJS application. 🚀


Course illustration
Course illustration

All Rights Reserved.