Angular-自定义方法装饰器,在方法的开始和结束时触发console.log() [英] Angular - Custom method decorator which triggers console.log() at the beginning and end of a method

查看:385
本文介绍了Angular-自定义方法装饰器,在方法的开始和结束时触发console.log()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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. 方法开始处的控制台日志
  2. 方法末尾的控制台日志

示例:

没有装饰器:

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

推荐答案

方法装饰器完全可以完成您想做的事情.它拦截装饰方法的调用.因此,您可以在装饰方法调用之前和之后登录.

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

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

在此示例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

这篇关于Angular-自定义方法装饰器,在方法的开始和结束时触发console.log()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆