我想知道是否可以在Angular中创建自定义装饰器,当应用于方法时可以实现以下功能:
>在方法开头的控制台日志
>控制台日志在方法结束时
例:
没有装饰者:
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);
});
}
解决方法:
方法装饰器完全符合您的要求.它拦截了装饰方法的调用.因此,您可以在调用装饰方法之前和之后进行记录.
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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。