codelord.net

Code, Angular, iOS and more by Aviv Ben-Yosef

AngularJS: What's the difference between factory and service?

| Comments

When getting started with Angular it can be a bit overwhelming to try and make sense of all the different tools and types of components that are available to us.

A very popular example of this are Services and Factories: they seem so similar yet they both exist for some reason. You’re trying to understand whether there’s really any difference. No one wants to pick the “wrong one” or “make the wrong choice”.

Factories vs. Services

First, right off the bat I’ll say they’re pretty much equivalent. Why do we have them both, then? That’s for the gods of Angular to know. They both allow us to create an object that can then be used anywhere in our app.

Most important is to realize that both are singletons in your app, even though the name “factory” might imply differently.

Essentially, factories are functions that return the object, while services are constructor functions of the object which are instantiated with the new keyword.

To the code!

To the users of our services and factories it all looks the same. This code below would be written the same regardless of which was used:

1
2
3
angular.module('app').controller('TheCtrl', function($scope, SomeService) {
    SomeService.someFunction();
});

Here is a matching factory:

1
2
3
4
5
angular.module('app').factory('SomeService', function() {
    return {
        someFunction: function() {}
    };
});

This will result in an injectable object called SomeService with a single public function someFunction.

And here is a matching service:

1
2
3
angular.module('app').service('SomeService', function() {
    this.someFunction = function() {};
});

This will result in… well… the same injectable object as above.

What to do? Use factories!

Now that you know the difference and can see that there’s none really, I’d recommend just going with one and get on with coding. Which one? Factories are the popular choice in the Angular community. I went with this decision years ago and recently saw that it is also the recommended way according to John Papa’s (excellent) style guide.

“Maintaining AngularJS feels like Cobol 🤷…”

You want to do AngularJS the right way.
Yet every blog post you see makes it look like your codebase is obsolete. Components? Lifecycle hooks? Controllers are dead?

It would be great to work on a modern codebase again, but who has weeks for a rewrite?
Well, you can get your app back in shape, without pushing back all your deadlines! Imagine, upgrading smoothly along your regular tasks, no longer deep in legacy.

Subscribe and get my free email course with steps for upgrading your AngularJS app to the latest 1.6 safely and without a rewrite.

Get the modernization email course!

Comments