Rya*_*ton 6 javascript typescript angular-decorator angular
我想知道是否可以在Angular中创建自定义装饰器,当应用于方法时可以实现以下功能:
例:
没有装饰者:
getRelationshipSource() {
console.log('Entering getRelationshipSource method');
this.referenceDataService.getRefData('RLNSHPSC').subscribe(res => {
this.relationshipSource$.next(res);
});
console.log('Leaving getRelationshipSource method');
}
Run Code Online (Sandbox Code Playgroud)
随着装饰
@LogMethod()
getRelationshipSource() {
this.referenceDataService.getRefData('RLNSHPSC').subscribe(res => {
this.relationshipSource$.next(res);
});
}
Run Code Online (Sandbox Code Playgroud)
zgu*_*gue 18
方法装饰器完全符合您的要求.它拦截了装饰方法的调用.因此,您可以在调用装饰方法之前和之后进行记录.
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;
}
}
Run Code Online (Sandbox Code Playgroud)
在这个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;
}
}
Run Code Online (Sandbox Code Playgroud)
控制台输出如下所示:
Entering ngOnInit method
Entering Add method
Leaving Add method
Leaving ngOnInit method
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3623 次 |
| 最近记录: |