The old Factory vs Service question

Ok, I admit that Angular JS is new to me, but I have been persevering with a few projects and learning as I go along.

I wanted to ensure that I am using ‘best practices’ wherever possible. To this end, I am writing an app that uses Firebase, and I wanted to utilise the Firebase authentication back end as well.

I would like to package up all the authentication routines so that I only have one set of code that deals with the various authentication protocols and returns the authData information to all my other controllers.

At present, I have the authentication routines within a Factory. But in reading more online, it appears that the Angular Service is designed to be a singleton. That is essentially what I need, isn’t it? A singleton that will hold the authentication details and enable them to be shared amongst all my controllers?

Should I be setting authentication up within a Service instead? Are there any other performance or memory overhead with either method that I should be aware about?

There is a couple of resources I always refer my devs to when they invariably have this same questions.

TLDR; Factory seems the right type for what you want to do.

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.

The other argues basically there is little need for a service at all:

1 Like