Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In AngularJS why is convention to name a factory service

Tags:

angularjs

In most examples I find of using Services in angularJs I find that the service is really a factory. eg

angular.module('myModule').factory('customerService', [
        '$http',
        function ($http) {
            return {

                get: function () {
                    return doSomeStuff();
                }
            };
        }
    ]);

The author has created a factory but called it customerService instead of customerFactory. Why is this? Is there some stigma against factories or are angular services so super-cool that everyone wants kudos for writing them, even when they don't.

Also, to be clear to anyone answering this, I'm not asking for the comparative merits of factories or services I'm asking why the angular community is deliberately misnaming their objects.

like image 915
Twisted Avatar asked Oct 21 '22 00:10

Twisted


2 Answers

Factory is the most basic provider that you can specify external dependencies while constructing your services. This is what Angularjs documentation says about naming them.

https://docs.angularjs.org/guide/providers

Best Practice: name the factory functions as Factory (e.g., apiTokenFactory). While this naming convention is not required, it helps when navigating the codebase or looking at stack traces in the debugger.

So it is a developer's choice but surely not the recommended way.

like image 123
idursun Avatar answered Oct 27 '22 10:10

idursun


Although the code you posted does indeed register a service factory, the first parameter of $provide.factory() is the name of the service instance (services are singletons). This name is used by the $injector to determine which factory is called when you declare a dependency on the service. See more here:

https://docs.angularjs.org/api/auto/service/$provide

like image 26
user1620220 Avatar answered Oct 27 '22 10:10

user1620220