Raj
Raj

Reputation: 149

When to Use service and When to factory in AngularJS?

I have gone through lots of document and also refereed stack overflow post regarding this issue. I am still having confusion When to use Service and Factory.

Can any one Explain using Real World Example when to use what ?

Upvotes: 1

Views: 37

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136184

Common thing about service & factory is they are singleton objects, there instance gets created once per application.

Basically angular service does return an object by using new keyword, whether factory does return an object which you have created.

Service

app.service('myService', function(){
  this.myMethod = function(){
     return 'something';
  };
})

In above service we added one method myMethod which can be available to the the component whoever inject the service. Service does gives access to all of its properties which are assigned to its this context.

Factory

app.factory('myService', function(){
  //here you can do some initial work before creating an service object.
  //which is very advantageous part of service.
  var configuredVariable = 'configured';
  return {
     myMethod : function(){
         return 'something'+ configuredVariable;
     };
  }
})

You could have controller over object before creating it, you could do some configuration kind of setting before returning an object from a service.

More detailed answer here

Summary

When to Use service and When to factory in agularJS?

Used service whenever you don't won't to return an configurable object, If you want to configure the object you should go for an factory.

Upvotes: 1

Related Questions