array-uri - Angular 7: decorator personalizat pentru clasă distruge scope-ul componentului


Am un decorator care, la ngOnInit, scrie un console.log

log.decorator.ts

export function Log(): ClassDecorator {

    // 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);
            }
        };
    };
}

și un HelloComponent care folosește @Log() și importă un serviciu utilizat în 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: [``]
})
// if you remove @Log(), helloService.sayHello() works!
@Log()
export class HelloComponent implements OnInit  {

  constructor(private helloService: HelloService){}

  ngOnInit(){
    this.helloService.sayHello();
  }
}

dar acest lucru cauzează o excepție:

EROARE TypeError: Nu se poate citi proprietatea 'sayHello' a valoării nedefinite

dacă elimin @Log() din HelloComponent funcționează!

decoratorul pare să distrugă domeniul componentului pe:

ngOnInit.apply(this, args); // line 13: log.decorator.ts

după acest apel, this.helloService este undefined în ngOnInit al HelloComponent, dar fără @Log(), this.helloService este o instanță de HelloService.

Cum repar asta?

Exemplu live pe Stackblitz: https://stackblitz.com/edit/angular-7hhp5n

Răspuns #1

Funcția săgeată forțează contextul this să fie contextul lexical înconjurător și contextul său de execuție al funcției Log.

Pentru a avea contextul componentelor ar trebui să folosești o expresie simplă de funcție:

target.prototype.ngOnInit = function( ...args ) {
   ...
}

Stackblitz bifurcat