Search code examples
javascriptangularjsangular-decorator

Can we access $provide inside a decorator in Angular JS?


Recently I came across a quiz and the question is

Decorators use 

Select one:
a. Both
b. $delegate
c. None
d. $provide

I choose b.$delegate and the quiz says it is wrong and the quiz says the correct answer is a.Both.

So I was wondering if this is true, I thought that decorators are inside provider i.e. they are a service which is invoked by provider and they can use $delegate like in this example

 app.config(function ($provide) {
  $provide.decorator('movieTitle', function ($delegate) {
    return $delegate + ' - starring Keanu Reeves';
  });
});

also, in the decorator documentation it states that

This function will be invoked when the service needs to be instantiated and should return the decorated service instance. The function is called using the injector.invoke method and is therefore fully injectable. Local injection arguments:

$delegate - The original service instance, which can be monkey patched, configured, decorated or delegated to.

so, am I missing something or is the quiz wrong, or am I wrong, can someone please help me understand this.


Solution

  • Yes the right answer is both. As an example this is a piece of code where is set a decorator for the $log service using a custom service logEnchance to add custom functionality. In this case logEnchance make posts to a external log service.

    angular.module('angularApp').config(configureLogger);
    
    // The decorator allows us to inject custom behaviors
    function configureLogger($provide) {
    
        // registers a value/object that can be accessed by providers and services
        $provide.constant('logDecorator', logDecorator);
    
        // registers a decorator function
        // $provide.decorator intercept $log service letting us add custom functionality
        $provide.decorator('$log', logDecorator);
    
        // inject dependencies into logDecorator function
        logDecorator.$inject = ['$delegate', 'logEnchance'];
    
        function logDecorator($delegate, logEnchance) {
            // logEnchance is the service who modify the $log service
            logEnchance( $delegate );
            return $delegate;
        }
    }