编程语言
首页 > 编程语言> > javascript – 我们可以在Angular JS的装饰器中访问$provide吗?

javascript – 我们可以在Angular JS的装饰器中访问$provide吗?

作者:互联网

最近我遇到了一个测验,问题是

Decorators use 

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

我选择b.$delegate并且测验说这是错误的,测验说正确的答案是a.两个.

所以我想知道这是否属实,我认为装饰器在提供者内部,即他们是由提供者调用的服务,他们可以使用$delegate,就像在这个例子中一样

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

此外,它在decorator documentation中说明了这一点

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.

所以,我错过了什么或测验错了,或者我错了,有人可以帮助我理解这一点.

解决方法:

是的,正确的答案是两者.作为示例,这是一段代码,其中使用自定义服务logEnchance为$log服务设置装饰器以添加自定义功能.在这种情况下,logEnchance会将帖子发布到外部日志服务.

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;
    }
}

标签:javascript,angularjs,angular-decorator
来源: https://codeday.me/bug/20190706/1395364.html