简体   繁体   中英

Decorating a service provider in Angular

I'm working on a library that extends some of the functionality in ui.router for building out sets of application states. Currently I am managing this by defining a new provider in my library (let's call it enhancedState ) in the form:

myApp.provider('enhancedState', EnhancedState);

EnhancedState.$inject = ['$stateProvider'];
function EnhancedState ($stateProvider) {
  this.$stateProvider = $stateProvider;
}
EnhancedState.prototype = {
  /* fun new methods that wrap $stateProvider */
  $get: ['$state', function ($state) {
    /* maybe wrap some $state functionality too */
    return $state;
  }
};

I can then use my enhancedStateProvider in my application config to do fun new state definitions following the extended capabilities of my library.

I would prefer, however, to directly decorate the $stateProvider class. I am aware of Angular's $provider.decorate() utility, but as far as I can tell, it can only be used to decorate the generated service instances, not the provider.

Has anyone successfully used it to decorate providers, or is aware of a similar mechanism to do so in Angular 1.x?

Thanks!

You need AngularJS decorators (find decorator method). Check this plunker example. Based on this so post.

Example:

app.config(function($provide) {
  $provide.decorator('$state', function($delegate) {
    $delegate.customMethod = function(a) {
      console.log(a);
    };
    return $delegate;
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM