Skip to content

Instantly share code, notes, and snippets.

@tarekahsan709
Last active February 14, 2017 11:48
Show Gist options
  • Save tarekahsan709/b306623fce29bf1932382ca46a1d37f0 to your computer and use it in GitHub Desktop.
Save tarekahsan709/b306623fce29bf1932382ca46a1d37f0 to your computer and use it in GitHub Desktop.

The difference between angular js service and factory.

Service and Factory both just a simple function. Service acts as a constructor function but Factory is really just a function that gets called, which is why we have to return an object explicitly. We can create & return anything that's why Factory is much more powerful and flexible.

reference: https://toddmotto.com/factory-versus-service

Here's example of Service

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

Here's example of Factory

function InboxFactory($http) {
  function getEmails() {
    return $http.get('/emails');
  }
  return {
    getEmails: getEmails
  };
}
angular
  .module('app')
  .factory('InboxFactory', InboxFactory);

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 + "!";
    }
  }
});

But service also can do extra task as factory. Also we should use Service because services allow us to use ES6 classes.

reference: https://blog.thoughtram.io/angular/2015/07/07/service-vs-factory-once-and-for-all.html#services-allow-us-to-use-es6-classes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment