AngularJS services vs factory advantages and shortcomings

This question already has an answer here:

  • angular.service vs angular.factory 9 answers

  • Service vs Factory


    在这里输入图像描述

    The difference between factory and service is just like the difference between a function and an object

    Factory Provider

  • Gives us the function's return value ie. You just create an object, add properties to it, then return that same object.When you pass this service into your controller, those properties on the object will now be available in that controller through your factory. (Hypothetical Scenario)

  • Singleton

  • Reusable components

  • Can use other dependencies

  • Usually used when the service instance requires complex creation logic

  • Used for non configurable services

  • If you're using an object, you could use the factory provider.

  • Syntax: module.factory('factoryName', function);

  • Service Provider

  • Gives us the instance of a function (object)- You just instantiated with the 'new' keyword and you'll add properties to 'this' and the service will return 'this'.When you pass the service into your controller, those properties on 'this' will now be available on that controller through your service. (Hypothetical Scenario)

  • Singleton and will only be created once

  • Reusable components

  • Dependencies are injected as constructor arguments

  • Used for simple creation logic

  • If you're using a class you could use the service provider

  • Syntax: module.service('serviceName', function);

  • In below example I have define MyService and MyFactory . Note how in .service I have created the service methods using this.methodname. In .factory I have created a factory object and assigned the methods to it.

    AngularJS .service


    module.service('MyService', function() {
    
        this.method1 = function() {
           //..
           return functionValue;
        }
    
        this.method2 = function() {
           //..
           return functionValue;
        }
    });
    

    AngularJS .factory


    module.factory('MyFactory', function() {
    
        var factory = {}; 
    
        factory.method1 = function() {
           //..
        }
    
        factory.method2 = function() {
           //..
        }
    
        return factory;
    });
    

    Also Take a look at this beautiful stuffs

    Confused about service vs factory

    AngularJS Factory, Service and Provider

    Angular.js: service vs provider vs factory?

    链接地址: http://www.djcxy.com/p/77828.html

    上一篇: 角度服务变量没有更新

    下一篇: AngularJS服务与工厂的优点和缺点