angular2指令`无法使用输出元数据读取未定义的属性'subscribe'

时间:2016-06-11 15:37:46

标签: angular angular2-directives

关于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);
  }
}

enter image description here

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

enter image description here

1 个答案:

答案 0 :(得分:28)

您需要初始化输出:

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