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:
Example:
Without Decorator:
getRelationshipSource() {
console.log('Entering getRelationshipSource method');
this.referenceDataService.getRefData('RLNSHPSC').subscribe(res => {
this.relationshipSource$.next(res);
});
console.log('Leaving getRelationshipSource method');
}
With Decorator
@LogMethod()
getRelationshipSource() {
this.referenceDataService.getRefData('RLNSHPSC').subscribe(res => {
this.relationshipSource$.next(res);
});
}
An Angular Decorator is a function, using which we attach metadata to a class, method, accessor, property, or parameter. We apply the decorator using the form @expression , where expression is the name of the decorator. The Decorators are Typescript features and still not part of the Javascript.
Parameter decorators are applied to the constructor parameter of the class and are used when we need to tell Angular to inject a particular provider in a constructor. @Inject() is a widely used parameter decorator. We use this decorator to inject services in Angular classes.
There are four types of decorators in Angular: Class Decorators. Property Decorators. Method Decorators.
Decorators are functions that are invoked with a prefixed @ symbol, and immediately followed by a class , parameter, method or property. The decorator function is supplied information about the class , parameter or method, and the decorator function returns something in its place, or manipulates its target in some way.
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: `<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;
}
}
The console output looks like:
Entering ngOnInit method
Entering Add method
Leaving Add method
Leaving ngOnInit method
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With