-2

I am trying play with Angular factory and service. Anyone could tell me the difference between those two?

Does factory always returns a singleton, but service an instance?

Adam Lee
  • 24,710
  • 51
  • 156
  • 236
  • 6
    Google is your friend! [angular.service vs angular.factory](http://stackoverflow.com/questions/14324451/angular-service-vs-angular-factory) – CollinD Jan 09 '16 at 03:03

1 Answers1

0

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'
});

Now the same thing as a factory:

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

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.

We can see that a service is a constructor function whereas a factory is not. Somewhere deep inside of this Angular world, there’s this code that calls Object.create() with the service constructor function, when it gets instantiated. However, a factory function is really just a function that gets called, which is why we have to return an object explicitly.

no matter what we use, service() or factory(), it’s always a factory that is called which creates a provider for our service.

Basically the difference between the service and factory is as follows:

app.service('myService', function() {

  // service is just a constructor function
  // that will be called with 'new'

  this.sayHello = function(name) {
     return "Hi " + name + "!";
  };
});

app.factory('myFactory', function() {

  // factory returns an object
  // you can run some code before

  return {
    sayHello : function(name) {
      return "Hi " + name + "!";
    }
  }
});

Both of them 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.

Source: service vs factory

zangw
  • 43,869
  • 19
  • 177
  • 214