What are “decorators” and how are they used?

前端 未结 5 1822
抹茶落季
抹茶落季 2020-11-28 01:07

I\'m curious what exactly decorators are in AngularJS. There isn\'t much information online for decorators save for a blurb in the AngularJS documentation and a brief (albei

5条回答
  •  时光取名叫无心
    2020-11-28 01:23

    In short decorators can be described as follows :-

    A decorator function intercepts the creation of a service, allowing it to override or modify the behavior of the service.

    It uses the $provide service by angular and modify or replaces the implementation of another service

    $provide.decorator('service to decorate',['$delegate', function($delegate) {
      // $delegate - The original service instance, 
      //             which can be replaced, monkey patched, 
      //             configured, decorated or delegated to. 
      //             ie here what is there in the 'service to decorate'
    
      //   This function will be invoked, 
      //   when the service needs to be provided 
      //   and should return the decorated service instance.
      return $delegate;
    }]);
    

    Example:

    $provide.decorator('$log', ['$delegate', function($delegate) {
      // This will change implementation of log.war to log.error
      $delegate.warn = $delegate.error; 
      return $delegate;
    }]);
    

    Applications

    In addition to @JBland answer.

    • Application wide locale settings :-

      You can find an example here

    • Changiging default behaviour of and existing implementation of a service by angular service :-

      You can find an eample here

    • Switching behavior of a function in different environments.

提交回复
热议问题