AngularJS supports the concepts of “Separation of Concerns” using services architecture. Services are javascript functions and are responsible to do a specific tasks only. This makes them an individual entity which is maintainable and testable. Controllers, filters can call them as on requirement basis. Services are normally injected using dependency injection mechanism of AngularJS.

The difference between services and factories

Okay, so what is the difference between a service and a factory in AngularJS? As we all know, we can define a service like this:

app.service('MyService', function () {
  this.sayHello = function () {
    console.log('hello');
  };
});

.service() is a method on our module that takes a name and a function that defines the service. Pretty straight forward. Once defined, we can inject and use that particular service in other components, like controllers, directives and filters, like this:

app.controller('AppController', function (MyService) {
  MyService.sayHello(); // logs 'hello'
});

Okay, clear. Now the same thing as a factory:

app.factory('MyService', function () {
  var factory = {};
    factory.sayHello = function () {
      console.log('hello');
    }
  return factory;
});

Again, .factory() is a method on our module and it also takes a name and a function, that defines the factory. We can inject and use that thing exactly the same way we did with the service. Now what is the difference here?

Capture.PNG

The difference between factory and service is just like the difference between a function and an object

Factory Provider

  • Gives us the function’s return value ie. You just create an object, add properties to it, then return that same object.When you pass this service into your controller, those properties on the object will now be available in that controller through your factory. (Hypothetical Scenario)
  • Singleton and will only be created once
  • Reusable components
  • Factory are a great way for communicating between controllers like sharing data.
  • Can use other dependencies
  • Usually used when the service instance requires complex creation logic
  • Cannot be injected in .config() function.
  • Used for non configurable services
  • If you’re using an object, you could use the factory provider.
  • Syntax: module.factory('factoryName', function);

Service Provider

  • Gives us the instance of a function (object)- You just instantiated with the ‘new’ keyword and you’ll add properties to ‘this’ and the service will return ‘this’.When you pass the service into your controller, those properties on ‘this’ will now be available on that controller through your service. (Hypothetical Scenario)
  • Singleton and will only be created once
  • Reusable components
  • Services are used for communication between controllers to share data
  • You can add properties and functions to a service object by using the this keyword
  • Dependencies are injected as constructor arguments
  • Used for simple creation logic
  • Cannot be injected in .config() function.
  • If you’re using a class you could use the service provider
  • Syntax: module.service(‘serviceName’, function);

Sample Demo

In below example I have define MyService and MyFactory. Note how in .service I have created the service methods using this.methodname. In .factory I have created a factory object and assigned the methods to it.

AngularJS .service


module.service('MyService', function() {

    this.method1 = function() {
            //..method1 logic
        }

    this.method2 = function() {
            //..method2 logic
        }
});

AngularJS .factory


module.factory('MyFactory', function() {

    var factory = {}; 

    factory.method1 = function() {
            //..method1 logic
        }

    factory.method2 = function() {
            //..method2 logic
        }

    return factory;
});

One more thing, they are all Singletons…

Also keep in mind that in both cases, angular is helping you manage a singleton. Regardless of where or how many times you inject your service or function, you will get the same reference to the same object or function. (With the exception of when a factory simply returns a value like a number or string. In that case, you will always get the same value, but not a reference.)

For more Examples from TutorialsPoint

Advertisements