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?