簡體   English   中英

Angular 7:自定義類裝飾器銷毀組件范圍

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

我有一個裝飾器,在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);
            }
        };
    };
}

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

但這會導致異常:

錯誤TypeError:無法讀取未定義的屬性'sayHello'

如果我從HelloComponent刪除@Log()它的工作原理!

裝飾器似乎破壞了組件范圍:

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

在此調用之后,在HelloComponent this.helloServiceundefined ngOnInit ,但是沒有@Log()this.helloService是一個HelloService實例。

我該如何解決?

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

箭頭函數強制上下文this是封閉的詞匯上下文,它是Log函數的執行上下文。

要有組件上下文,您應該使用簡單的函數表達式:

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

分叉Stackblitz

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM