Categories

See More
Popular Forum

MBA (4887) B.Tech (1769) Engineering (1486) Class 12 (1030) Study Abroad (1004) Computer Science and Engineering (988) Business Management Studies (865) BBA (846) Diploma (746) CAT (651) B.Com (648) B.Sc (643) JEE Mains (618) Mechanical Engineering (574) Exam (525) India (462) Career (452) All Time Q&A (439) Mass Communication (427) BCA (417) Science (384) Computers & IT (Non-Engg) (383) Medicine & Health Sciences (381) Hotel Management (373) Civil Engineering (353) MCA (349) Tuteehub Top Questions (348) Distance (340) Colleges in India (334)
See More

AngularJS: Service vs provider vs factory

General Tech Bugs & Fixes
Max. 2000 characters
Replies

usr_profile.png
Ekta Singhania

User

( 9 months ago )

What are the differences between a ServiceProvider and Factory in AngularJS?

usr_profile.png
Harsh Vashishth

User

( 9 months ago )

I found that all the Angular terms were intimidating for beginners. We started off with this cheatsheet that was a little easier for our programmers to understand while learning Angular demisx.github.io/angularjs/2014/09/14/…. Hope this helps your team too

usr_profile.png
Raman Tripathi

User

( 9 months ago )

In my opinion, the best way to understand the difference is using Angular's own documentation: docs.angularjs.org/guide/providers it is extremely well explained and uses a peculiar example to help you understand it. 

usr_profile.png
Jasmin Bhasin

User

( 9 months ago )

From the AngularJS mailing list I got an amazing thread that explains service vs factory vs provider and their injection usage. Compiling the answers:

Services

Syntax: module.service( 'serviceName', function ); 
Result: When declaring serviceName as an injectable argument you will be provided with an instance of the function. In other words new FunctionYouPassedToService().

Factories

Syntax: module.factory( 'factoryName', function ); 
Result: When declaring factoryName as an injectable argument you will be provided with the value that is returned by invoking the function reference passed to module.factory.

Providers

Syntax: module.provider( 'providerName', function ); 
Result: When declaring providerName as an injectable argument you will be provided with (new ProviderFunction()).$get(). The constructor function is instantiated before the $get method is called - ProviderFunction is the function reference passed to module.provider.

Providers have the advantage that they can be configured during the module configuration phase.

See here for the provided code.

Here's a great further explanation by Misko:

provide.value('a', 123);

function Controller(a) {
  expect(a).toEqual(123);
}

In this case the injector simply returns the value as is. But what if you want to compute the value? Then use a factory

provide.factory('b', function(a) {
  return a*2;
});

function Controller(b) {
  expect(b).toEqual(246);
}

So factory is a function which is responsible for creating the value. Notice that the factory function can ask for other dependencies.

But what if you want to be more OO and have a class called Greeter?

function Greeter(a) {
  this.greet = function() {
    return 'Hello ' + a;
  }
}

Then to instantiate you would have to write

provide.factory('greeter', function(a) {
  return new Greeter(a);
});

Then we could ask for 'greeter' in controller like this

function Controller(greeter) {
  expect(greeter instanceof Greeter).toBe(true);
  expect(greeter.greet()).toEqual('Hello 123');
}

But that is way too wordy. A shorter way to write this would be provider.service('greeter', Greeter);

But what if we wanted to configure the Greeter class before the injection? Then we could write

provide.provider('greeter2', function() {
  var salutation = 'Hello';
  this.setSalutation = function(s) {
    salutation = s;
  }

  function Greeter(a) {
    this.greet = function() {
      return salutation + ' ' + a;
    }
  }

  this
								
usr_profile.png
Rukhsar Fatima

User

( 9 months ago )

TL;DR 

1) When you’re using a Factory you create an object, add properties to it, then return that same object. When you pass this factory into your controller, those properties on the object will now be available in that controller through your factory.

app.controller(‘myFactoryCtrl’, function($scope, myFactory){
  $scope.artist = myFactory.getArtist();
});

app.factory(‘myFactory’, function(){
  var _artist = Shakira’;
  var service = {};

  service.getArtist = function(){
    return _artist;
  }

  return service;
});


2) When you’re using Service, AngularJS instantiates it behind the scenes with the ‘new’ keyword. Because of that, 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.

app.controller(‘myServiceCtrl’, function($scope, myService){
  $scope.artist = myService.getArtist();
});

app.service(‘myService’, function(){
  var _artist = Nelly’;
  this.getArtist = function(){
    return _artist;
  }
});



3) Providers are the only service you can pass into your .config() function. Use a provider when you want to provide module-wide configuration for your service object before making it available.

app.controller(‘myProvider’, function($scope, myProvider){
  $scope.artist = myProvider.getArtist();
  $scope.data.thingFromConfig = myProvider.thingOnConfig;
});

app.provider(‘myProvider’, function(){
 //Only the next two lines are available in the app.config()
 this._artist = ‘’;
 this.thingFromConfig = ‘’;
  this.$get = function(){
    var that = this;
    return {
      getArtist: function(){
        return that._artist;
      },
      thingOnConfig: that.thingFromConfig
    }
  }
});

app.config(function(myProviderProvider){
  myProviderProvider.thingFromConfig = This was set in config’;
});



Non TL;DR

1) Factory 
Factories are the most popular way to create and configure a service. There’s really not much more than what the TL;DR said. You just create an object, add properties to it, then return that same object. Then when you pass the factory into your controller, those properties on the object will now be available in that controller through your factory. A more extensive example is below.

app.factory(‘
								 								 
							usr_profile.png
							
SHADMON KUDCHIKAR

User

( 5 months ago )

Angularjs Services are functions or objects that contains reusable code that can get consumed accross app by controllers, directives, filters and other services using Dependency Injection Mechanism of Angularjs.

Traditional Provider Method

The most fundamental service creation function is the provider function. Creating services with it allows you to create a configurable provider object. The provider knows how to create the resulting service.

The basic process is that the $provide service creates a provider which contains a function that is used to create a service.

The first function on the $provide service we’ll look at is the provider function. It’s the most fundamental way to create a service. All of the other methods of creating services(factory, service, and value method) which we’ll learn are just wrappers around the provider function (except constant method).

To use the provider function directly, you simply call the function and pass it a name and a function that will define the underlying provider.

The provider created for each service, will be given a name that is the name you specify for the service with the word provider appended to it. So in the below example, the name of the service we will inject into our other components, will be ‘oauth’, and the name of the provider we will inject in module config method will be oauthProvider to configure our oauth service.

Provider function requires service name as first parameter and second parameter it require is the function which must contain a property named $get.

The return value of the function assigned to $get property will represent our service that gets injected.

Popular Factory Method

The factory function is much easier to use than the above provider method. If you don’t need to configure the provider, like we did in the last example, then use the factory function which is much simpler and readable way to create your services.

Flexible Service Method

The next service creation function is Service, which is simply a wrapper around the factory function. When you call the service function, it will internally call the factory function, which will then call the provider function.

The only difference is that the function you passed to the service method will be treated as a constructor function and called with the JavaScript “new” operator. You would use the service method instead of the factory method if you specifically needed your function to be treated as a constructor and called with the “new” operator.

There are several reasons why you may want that behavior. One is if you have defined an inheritance hierarchy in your code. Creating an instance with “new” will make sure that your instantiated object properly inherits from its prototypes.

There are five functions you can use to create an Angular service. All of these functions may be called on the built-in provide service. All of them are also exposed on the module object as a convenience. You can learn more about this methods and theri real world implementation here: https://kudchikarsk.com/angularjs-service/

what's your interest