0 votes
in Angular by
What is the Difference Between Factory and Service?

1 Answer

0 votes
by

Factory and Service are different ways of doing DI (Dependency injection) in Angular. Please read the previous question to understand what is DI.

So when we define DI using service as shown in the code below. This creates a new GLOBAL instance of the Logger object and injects it in to the function.

HTML
app.service("Logger", Logger); // Injects a global object

When you define DI using a factory it does not create a instance. It just passes the method and later the consumer internally has to make calls to the factory for object instances.

HTML
app.factory("Customerfactory", CreateCustomer);

Below is a simple image which shows visually how DI process for Service is different than Factory.

Image 20

 FactoryService
UsageWhen we want to create different types of objects depending on scenarios. For example, depending on scenario, we want to create a simple Customer object , or Customer with Address object or Customer with Phone object. See the previous question for more detailed understanding.When we have utility or shared functions to be injected like Utility , Logger, Error handler, etc.
InstanceNo Instance created. A method pointer is passed.Global and Shared instance is created.
 

Related questions

0 votes
asked Dec 31, 2023 in Angular by DavidAnderson
0 votes
asked Dec 29, 2023 in Angular by DavidAnderson
...