angular service available at configuration phase

前端 未结 1 1667
小鲜肉
小鲜肉 2021-01-24 00:37

I want to move some of the repetitive logic out in a reusable service, which must be available in a config phase. And possibly have access to $xxxProvider

相关标签:
1条回答
  • 2021-01-24 01:06

    For accessing your service provider in the config block, this should work just fine:

    app.service('myService', function (/* dependencies */) {
      // service stuff..
    
      return this; 
    });
    
    app.config(function ($provide) {
      $provide.decorator('myService', function ($delegate) {
        // $delegate refers to 'myService'. 
        // You can modify its behaviour and what not in here.
    
        return $delegate;
      });
    });
    

    I'm not crystal clear on what you are looking for, but this 'just works'.

    Do note, that the service registration needs to come before the config block if they reside in the same file. A way to overcome this, would be to extract your service into a separate module and inject it as a dependency to your main module. Something like this:

    var serviceModule = angular.module('serviceModule', []);
    
    serviceModule.service('myService', function () {});
    
    var mainModule = angular.module('main', ['serviceModule']);
    
    mainModule.config(function ($provide) {
      $provide.decorator('myService', function ($delegate) {});
    });
    

    JsBin: http://jsbin.com/pasiquju/2/edit

    Edit

    I've now put together a rough example of how you could do the following:

    1. Register your own custom provider constructor, that returns an object.
    2. Inject another provider into your own provider, passing through functionality from one constructor to another.
    3. Register a secondary service, that gets injected into the provider constructor.
    4. Pass some more functionality from the app.config block to your provider constructor.
    5. Inject the instance returned by the constructor into a controller.
    6. Output the end data from the instance returned by the constructor, with args.

    This should cover the needs specified:

    • Prone to DI, from providers.
    • Prone to DI, from services.
    • Available during config phase.

    JsBin: http://jsbin.com/jenumobi/2/edit

    And here's the documentation for the provider shorthand methods, and how they differ. As you can clearly see, the provider core function is the one with the most options available to it - but also the hardest to work with, for obvious reasons.

    I hope that will do enough for you, and give you some sort of idea on how to create your own $stateProvider extension! I've done my best to document the code in the JsBin to make it easier to understand just how it all ties together.

    0 讨论(0)
提交回复
热议问题