Angular - 自定义方法装饰器,它在方法的开头和结尾触发console.log()

时间:2017-10-26 11:54:37

标签: javascript angular typescript angular-decorator

我想知道是否可以在Angular中创建自定义装饰器,当应用于方法时可以实现以下功能:

  1. 方法开头的控制台日志
  2. 方法结束时的控制台日志
  3. 示例:

    没有装饰者:

    getRelationshipSource() {
      console.log('Entering getRelationshipSource method');
      this.referenceDataService.getRefData('RLNSHPSC').subscribe(res => {
        this.relationshipSource$.next(res);
      });
      console.log('Leaving getRelationshipSource method');
    }
    

    使用装饰器

    @LogMethod()
    getRelationshipSource() {
      this.referenceDataService.getRefData('RLNSHPSC').subscribe(res => {
        this.relationshipSource$.next(res);
      });
    }
    

1 个答案:

答案 0 :(得分:15)

方法装饰器完全符合您的要求。它拦截了装饰方法的调用。因此,您可以在调用装饰方法之前和之后进行记录。

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

在此SAMPLE APP中,我在HelloComponent中使用了它。

import { Component, Input } from '@angular/core';
import { log } from './log.decorator';

@Component({
  selector: 'hello',
  template: `<h1>Hello {{name}}!</h1>`,
  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;
  }
}

控制台输出如下:

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