0

I think I had the misconception before that an AngularJS factory is for object creation or functions, while an AngularJS service is for HTTP requests.

Another question talked about this, but it didn't clarify some of the most fundamental concepts.

It looks like their end result is exactly the same -- to get a what is called a "service object". We can usually use factory() or service() interchangeably, and it just matter how the service object is created.

In the case of a factory, the object is returned as is:

angular.module("myApp", [])
    .factory("myService", function() {
        return {   // the awesome service object
            foo: 123,
            doSomething: function() { }
        };
     });

In the case of a service, AngularJS will use that function as a contructor function, with a new keyword, to create the service object and return to the user, when the user uses myService.doSomething() or myService.foo in the user's code.

angular.module("myApp", [])
    .service("myService", function() {
        // I am the awesome service object when AngularJS uses
        //   the keyword "new" on the above anonymous function. 
        //   "this" will point to myself.
        this.foo = 123;
        this.doSomething = function() { };
     });

So an AngularJS factory or service can actually both do exactly the same thing (such as fetching data from the server), but they just differ how the service object is created.

If we just use the usual, simple JavaScript object literal, we can just use factory(), but the only case we would use service() instead is that, if we want to create a base class, and then use inheritance to create subclasses, and now we have these constructor functions, and to use constructors, we have to use service().

Is this concept correct for AngularJS?

Community
  • 1
  • 1
nonopolarity
  • 146,324
  • 131
  • 460
  • 740
  • Not sure about others, but I use factory when I want to bind functions to prototype. like this: `.factory("myClass", function() { function myClass(){} myClass.prototype.dosomething = function(){}; return myClass;})` – rabbit.aaron Feb 29 '16 at 01:58
  • 2
    yes, `.service` takes a constructor function and calls `new` on it, whereas `.factory` takes a factory function that returns the object. In both cases, you are left with a singleton "service" object that is injectable via Angular's DI framework – New Dev Feb 29 '16 at 02:02
  • Yes. I agree with NewDev. This might help too: http://stackoverflow.com/questions/15666048/angularjs-service-vs-provider-vs-factory/25092033#25092033 – Michael Kang Feb 29 '16 at 02:52
  • Possible duplicate of [angular.service vs angular.factory](http://stackoverflow.com/questions/14324451/angular-service-vs-angular-factory) – georgeawg Feb 29 '16 at 03:09
  • This issue is not specific to Angular. It applies to all frameworks and languages. You (have to) use a factory if calling `new` isn't enough or possible. – a better oliver Feb 29 '16 at 12:37

0 Answers0