You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The $provide service has a number of methods for registering components with the $injector. Many of these functions are also exposed on angular.Module.
decorator(name, decorator);
Register(注册) a decorator function with the $injector. A decorator function intercepts(拦截) the creation of a service, allowing it to override(覆盖) or modify(修改) the behavior of the service. The return value of the decorator function may be the original service, or a new service that replaces (or wraps and delegates(代表) to the original service.
This function will be invoked(运行) when the service needs to be provided(需要被提供) 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 replaced, monkey patched, configured, decorated or delegated to.
angular.module('app').config(config);// 在模块启动时更改原有服务逻辑config.$inject=['$provide'];// 注入$provide以便调用decorator方法functionconfig($provide){// 要修改的目标OriginService$provide.decorator('OriginService',OriginServiceDecorator);// 注入$delegate来获得原有的服务实例,注入其他服务来实现逻辑OriginServiceDecorator.$inject=['$delegate','other'];functionOriginServiceDecorator($delegate,other){varfirstMethod=$delegate.firstMethod;functionnewFirstMethod(){// new service functionother.someFunc();returnfirstMethod.apply($delegate,arguments);}$delegate.firstMethod=newFirstMethod;varsecondMethod=$delegate.secondMethod;functionnewSecondMethod(){other.someFunc();returnsecondMethod.apply($delegate,arguments);}$delegate.secondMethod=newSecondMethod;// 通过以上的修改,原有的OriginService已经被我们新增加了自己的逻辑,// 并且没有改变原有OriginService实现逻辑。仅在app模块以及其依赖模块上有效。return$delegate;}}
The text was updated successfully, but these errors were encountered:
前提 依赖注入与$injector
思考,能否在$injector的逻辑中,存在修改已注册依赖的入口,让我们针对具体对象能够配置对应的依赖,并且没有破坏原有依赖自身的实现逻辑?
依赖注入关注各个对象之间的关系,ng中将可以被依赖注入的对象,称为服务,以下将对依赖的修改统称为对服务的修改。
什么是decorator
首先来看ng官方的定义:
The $provide service has a number of methods for registering components with the $injector. Many of these functions are also exposed on angular.Module.
ng对decorator方法的划分也是在一个$provide的服务上,这样我们可以通过注入$provide来调用。下面来看具体的使用方式。
简单来说:
decorator的本质是在$injector上注册了一个方法。
这个方法可以拦截一个服务的创建,并且可以覆盖或修改这个服务的行为。
该方法应该有一个返回值,这个值可以是原来的服务(即你没有做任何修改),也可以是一个替换或者修改并代表了原服务的一个全新的服务。
很顺利,ng给我们提供了一个入口来切入服务创建的过程,并且能够写入自身的逻辑。
就是本文的主角:decorator 方法。
怎样使用decorator
结合我们的问题与ng给出的定义,很清楚的可以得到实现过程,首先来看,decorator方法在代码中使用:
decorator(name, decorator);
要拿到原有服务,我们需要为这个方法注入$delegate,同样的,我们可以注入更多的服务,来丰富自定义逻辑。
剩下的就很简单了,下面是一个简单的代码示例。
The text was updated successfully, but these errors were encountered: