简体   繁体   English

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

[英]Angular 7: custom class decorator destroy component scope

I have a decorator that on ngOnInit write a console.log 我有一个装饰器,在ngOnInit写一个console.log

log.decorator.ts 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);
            }
        };
    };
}

and a HelloComponent that use @Log() and import a service used in ngOnInit HelloComponent使用@Log()和导入使用的服务ngOnInit

hello.component.ts 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();
  }
}

but this causes an exception: 但这会导致异常:

ERROR TypeError: Cannot read property 'sayHello' of undefined 错误TypeError:无法读取未定义的属性'sayHello'

if i remove @Log() from HelloComponent it works! 如果我从HelloComponent删除@Log()它的工作原理!

the decorator seems to destroy the component scope on: 装饰器似乎破坏了组件范围:

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

after this call, this.helloService is undefined in the ngOnInit of HelloComponent , but without @Log() , this.helloService is a HelloService instance. 在此调用之后,在HelloComponent this.helloServiceundefined ngOnInit ,但是没有@Log()this.helloService是一个HelloService实例。

How do I fix this? 我该如何解决?

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

Arrow function forces context this to be the enclosing lexical context and it's execution context of Log function. 箭头函数强制上下文this是封闭的词汇上下文,它是Log函数的执行上下文。

To have component context you should use simple function expression: 要有组件上下文,您应该使用简单的函数表达式:

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

Forked Stackblitz 分叉Stackblitz

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM