I have been extensively researching decorators in TypeScript, but I have not been able to find comprehensive documentation that suits my specific needs.
After exploring two possible solutions - AOP and Decorator, it seems like AOP is not fully functional yet.
My situation involves implementing a security library where I need to invoke methods "enterAction" and "leaveAction" whenever the current page changes.
Given that I have Angular/Ionic lifecycle events for page changes (load/leave), I prefer to centralize the overrides in one place rather than modifying each individual page component. This way, when adding a new page, I won't forget to implement it.
Hence, my plan was to add a decorator on each page class which would incorporate calls to my secure library's actions based on the load/leave events being triggered.
Currently, I am able to create a class decorator. However, I am unsure of how to properly override method calls.
This is how I have defined my class decorator:
@security
@Component({
selector: 'my-app',
template: '<h1>Hello Angular!</h1>'
})
export class AppComponent implements OnInit {
private toto= "demo";
constructor() {
console.log("construct!");
}
ngOnInit() {
console.log('onInit');
this.method1();
}
method1() {
console.log('method 1 : '+ this.toto);
}
}
function security<TFunction extends Function>(target: TFunction): TFunction {
var method1 = target.prototype.method1;
Object.defineProperty(target.prototype, 'method1', {
value: function() {
console.log('enterAction here');
// How to call real method1() here ?
// Call of method1() will fail since it don't know AppCompnent.toto here
return '';
}
});
return target;
}
Regards,
EDIT
Eventually, I discovered an alternative approach that doesn't involve using decorators to solve my issue.