Confused about Service vs Factory

后端 未结 20 2453
轻奢々
轻奢々 2020-11-22 08:49

As I understand it, when inside a factory I return an object that gets injected into a controller. When inside a service I am dealing with the object using this

20条回答
  •  攒了一身酷
    2020-11-22 09:29

    “Factory” and “Service” are different ways of doing DI (Dependency injection) in angular.

    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.

    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.

    app.factory("Customerfactory", CreateCustomer);
    

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

    enter image description here

    Factory should be used When 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. Here is a detailed explanation of this paragraph

    Service should be used When we have utility or shared functions to be injected like Utility , Logger , Error handler etc.

提交回复
热议问题