Angular - Custom method decorator which triggers console.log() at the beginning and end of a method

前端 未结 1 1414
甜味超标
甜味超标 2021-02-06 07:25

I would like to know if it is possible to create a custom decorator in Angular which when applied to a method can achieve the following functionality:

  1. console log
1条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-06 08:22

    A method decorator does exactly what you want to do. It intercepts the call of the decorated method. So you are able to log before and after the call of the decorated method.

    log.decorator.ts

    export function log( ) : MethodDecorator {
      return function(target: Function, key: string, descriptor: any) {
    
        const originalMethod = descriptor.value; 
    
        descriptor.value =  function (...args: any[]) {
    
          console.log(`Entering ${key} method`);
          const result = originalMethod.apply(this, args);
          console.log(`Leaving ${key} method` );
    
          return result;
        }
    
        return descriptor;
      }
    }
    

    In this SAMPLE APP I used it in the HelloComponent.

    import { Component, Input } from '@angular/core';
    import { log } from './log.decorator';
    
    @Component({
      selector: 'hello',
      template: `

    Hello {{name}}!

    `, styles: [`h1 { font-family: Lato; }`] }) export class HelloComponent { @Input() name: string; @log() ngOnInit() { this.Add(10, 32); } @log() private Add(a: number, b: number) : number { return a + b; } }

    The console output looks like:

    Entering ngOnInit method
    Entering Add method
    Leaving Add method
    Leaving ngOnInit method
    

    0 讨论(0)
提交回复
热议问题