$provide outside config blocks

后端 未结 2 580
情话喂你
情话喂你 2020-11-28 16:51

I\'m certainly missing some fundamental point about the injector, but I fail to understand why exactly this

angular.module(\'app\').config(function ($provide         


        
2条回答
  •  误落风尘
    2020-11-28 17:26

    After some Angular injector study I was able to give an exhaustive answer to my own question.

    Essentially, $injector in config blocks and provider constructor functions and $injector everywhere else are two different services with the same name, which are defined on internal provider/instance cache explicitly, together with $provide (this one is being defined in provider cache, hence it can be injected in config only).

    While generally not recommended because of probable race conditions, it is possible to expose internal services to instance cache and make config-specific $provide and $injector available for injection after config phase has ended:

    app.config(function ($provide, $injector) {
      $provide.value('$providerInjector', $injector);
      $provide.value('$provide', $provide);
    });
    

    The possible applications are configuring service providers any time (if possible)

    app.run(function ($providerInjector) {
      var $compileProvider = $providerInjector.get('$compileProvider');
      ...
    });
    

    and defining new components at run-time

    app.run(function ($provide) {
      $provide.controller(...);
      ...
    });
    

提交回复
热议问题