Angular 7:自定义类装饰器销毁组件范围

ar0*_*968 5 arrays typescript angular angular7

我有一个装饰师,ngOnInit写一个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);
            }
        };
    };
}
Run Code Online (Sandbox Code Playgroud)

和一个HelloComponent使用@Log()和导入使用的服务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();
  }
}
Run Code Online (Sandbox Code Playgroud)

但这会导致异常:

错误TypeError:无法读取未定义的属性'sayHello'

如果我@Log()HelloComponent它删除工作!

装饰器似乎破坏了组件范围:

ngOnInit.apply(this, args); // line 13: log.decorator.ts
Run Code Online (Sandbox Code Playgroud)

这个电话后,this.helloServiceundefinedngOnInitHelloComponent,但没有@Log(),this.helloService就是一个HelloService实例.

我该如何解决?

Stackblitz上的实例:https://stackblitz.com/edit/angular-7hhp5n

yur*_*zui 9

箭头函数强制上下文this是封闭的词汇上下文,它是Log函数的执行上下文.

要有组件上下文,您应该使用简单的函数表达式:

target.prototype.ngOnInit = function( ...args ) {
   ...
}
Run Code Online (Sandbox Code Playgroud)

分叉Stackblitz