ngOnDestroy method is overridden with listed decorator. The actual problem with it is that wrong context is applied to originalFunction in
originalFunction.apply(target, arguments);
In case of method/property decorators target argument is class prototype for instance properties/methods:
export const ON_DESTROY_SYMBOL = Symbol();
export function Decorator() {
return (target: any, propertyName: string) => {
target[ON_DESTROY_SYMBOL] = target.ngOnDestroy;
target.ngOnDestroy = function() {
this[ON_DESTROY_SYMBOL]();
console.log('Component destroy event successfully handled!');
}
}
}
If ngOnDestroy method doesn't necessarily exist but the decorator should be applied any way, it can be class decorator instead, where target is class constructor:
export function Decorator() {
return (target: any, propertyName: string) => {
target.prototype[ON_DESTROY_SYMBOL] = target.prototype.ngOnDestroy || () => {};
target.prototype.ngOnDestroy = function() {
this[ON_DESTROY_SYMBOL]();
console.log('Component destroy event successfully handled!');
}
}
}
...
Decorator()
Component(...)
class ...
ngOnInithas nothing to do about it. As you can see in the demo router is properly injected inside constructor.