angular2 指令`无法读取 属性 'subscribe' of undefined` 输出元数据

angular2 directive `Cannot read property 'subscribe' of undefined` with outputs metadata

关于 Angular2 指令,我想使用 outputs 而不是 @Output 因为我有很多自定义事件并且想保持 DRY。

但是,我有 TypeError: Cannot read property 'subscribe' of undefined,我不知道为什么会这样。

http://plnkr.co/edit/SFL9fo?p=preview

import { Directive } from "@angular/core";

@Directive({
  selector: '[my-directive]',
  outputs: ['myEvent']
}) 
export class MyDirective {
  constructor() {
    console.log('>>>>>>>>> this.myEvent', this.myEvent);
  }
}

这是使用该指令的应用程序组件

您需要初始化输出:

import { Directive } from "@angular/core";

@Directive({
  selector: '[my-directive]',
  outputs: ['myEvent']
}) 
export class MyDirective {
  myEvent:EventEmitter<any> = new EventEmitter(); // <-----

  constructor() {
    console.log('>>>>>>>>> this.myEvent', this.myEvent);
  }
}

您还可以使用 @HostListener 装饰器:

@Directive({
  selector: '[my-directive]'
}) 
export class MyDirective {
  @HostListener('myEvent')
  myEvent:EventEmitter<any> = new EventEmitter(); // <-----

  constructor() {
    console.log('>>>>>>>>> this.myEvent', this.myEvent);
  }
}