arrays - Angular 7 : custom class decorator destroy component scope

标签 arrays angular typescript 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);
            }
        };
    };
}

和一个使用 @Log() 并导入在 ngOnInit

中使用的服务的 HelloComponent

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

但这会导致异常:

ERROR TypeError: Cannot read property 'sayHello' of undefined

如果我从 HelloComponent 中删除 @Log() 它会起作用!

装饰器似乎破坏了组件作用域:

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

在这个调用之后,this.helloServiceHelloComponentngOnInit中是undefined,但是没有@Log()this.helloService是一个HelloService实例。

我该如何解决这个问题?

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

最佳答案

箭头函数强制上下文 this 成为封闭的词法上下文,它是 Log 函数的执行上下文。

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

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

Forked Stackblitz

关于arrays - Angular 7 : custom class decorator destroy component scope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52986193/

相关文章:

c++ - 如何将二维数组相互分配?

javascript - 如何使用 React 从对象数组中获取数据,通过 API 端点将其传递到 .fetch() 所需的对象值?

javascript - 如何在读取第二个值之前禁用 NFC 事件监听器?

Typescript 错误作为警告

arrays - 元素数组不会被接口(interface)填充

arrays - JavaScript null 和加号 (+) 运算符

angular - 如何在 Angular2 的某些 div 中只读所有输入?

javascript - 如何在 <td> 标签下使用 Accordion? Angular 9

reactjs - typescript react : polymorphic refs for any HTMLElement

javascript - attr.checked 不适用于动态添加的元素