My dilemma lies in the fact that I have a decorator which, when applied on ngOnInit
, initiates a console.log
.
log.decorator.ts
export function Log(): ClassDecorator {
// The Decorator Factory
return (target: Function) => {
const ngOnInit: Function = target.prototype.ngOnInit;
target.prototype.ngOnInit = ( ...args ) => {
console.log('ngOnInit:', target.name);
if ( ngOnInit ) {
ngOnInit.apply(this, args);
}
};
};
}
Additionally, there is a HelloComponent
that utilizes @Log()
and imports a service required in ngOnInit
.
hello.component.ts
import { Component, Input, OnInit } from '@angular/core';
import { Log } from './log.decorator';
import { HelloService } from './hello.service';
@Component({
selector: 'hello',
template: `<p>Hello! thanks for help and open the browser console for see the error!</p>`,
styles: [``]
})
// By removing @Log(), helloService.sayHello() functions properly!
@Log()
export class HelloComponent implements OnInit {
constructor(private helloService: HelloService){}
ngOnInit(){
this.helloService.sayHello();
}
}
This setup results in an exception:
ERROR TypeError: Cannot read property 'sayHello' of undefined
If I exclude @Log()
from HelloComponent
, everything works as expected.
It appears that the decorator interferes with the scope of the component at:
ngOnInit.apply(this, args); // line 13: log.decorator.ts
Following this call, this.helloService
stands as undefined
within the ngOnInit
of HelloComponent
. Conversely, without @Log()
, this.helloService
represents an instance of HelloService
.
I am seeking advice on rectifying this issue. How should I proceed?
For demonstration purposes, you can access a live example on Stackblitz: https://stackblitz.com/edit/angular-7hhp5n