What is the type friendly injection?

后端 未结 4 442
忘了有多久
忘了有多久 2021-02-03 23:18

In the AngularJS documentation, there is an explanation of the differences between a factory, a service, a value, a constant and a provider .

At the end, we have a compa

4条回答
  •  死守一世寂寞
    2021-02-03 23:37

    In AngularJS, you can inject dependencies in multiple ways:

    • in the directive link function by position
    • in the directive definition by name
    • in the controller function by name
    • in the factory function by name
    • in the service function by type

    Type friendly injection allows you to implicity invoke a constructor function by reference:

    myApp.service('Pattern', ["Infinity", RegExp]);
    

    rather than by explicity using the new keyword:

    myApp.factory('Pattern', 
     ["Infinity", function(Infinity) 
      {
      return new RegExp(Infinity);
      } 
     ]);
    

    OR

    function goInfinity(Infinity)
      {
      return new RegExp(Infinity);
      } 
    
    goInfinity.$inject = ["Infinity"];
    myApp.factory('Pattern', goInfinity);
    

    The Service recipe produces a service just like the Value or Factory recipes, but it does so by invoking a constructor with the new operator. The constructor can take zero or more arguments, which represent dependencies needed by the instance of this type.

    Eager initialization means that a constant recipe must return a constructor in order to use the aforementioned syntax:

    function RegExpConstant() 
      {
      return new RegExp(Infinity);
      } 
    
    myApp.constant('Pattern', RegExpConstant)
    

    rather than returning a function, object, or literal value.

    The nomenclature comes from Java:

    A service is a well-known set of interfaces. A service provider is a specific implementation of a service. A factory is an object that returns an object reference to another object

    References

    • Dependency Injection in Angular 2

    • The main goals of Angular 2 and how they will be achieved

    • Vojta Jina: Dependency Injection - NG-Conf

    • AngularJS: Developer Guide - Providers, Service Recipe

    • AngularJS: The Bad Parts

    • Dependency Injection: Syntax Sugar Over Function Composition

    • ServiceFinder (JAX-WS RI)

提交回复
热议问题