angular2指令“无法读取未定义的属性" subscribe",带有输出元数据 [英] angular2 directive `Cannot read property 'subscribe' of undefined` with outputs metadata

查看:112
本文介绍了angular2指令“无法读取未定义的属性" subscribe",带有输出元数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Regarding Angular2 directive, I wanted to use outputs instead of using @Output because I have many custom events and wanted to keep DRY.

但是,我正在使用TypeError: Cannot read property 'subscribe' of undefined,但我不知道它为什么会发生.

However, I am having TypeError: Cannot read property 'subscribe' of undefined, and I don't know why it's happening.

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

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

And this is app component that uses this directive

推荐答案

您需要初始化输出:

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

这篇关于angular2指令“无法读取未定义的属性" subscribe",带有输出元数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆