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

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

问题描述

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

但是,我遇到了TypeError: Cannot read property 'subscribe' of undefined,我不知道为什么会这样.

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

解决方案

需要初始化输出:

import { Directive } from "@angular/core";@指示({选择器:'[我的指令]',输出:['myEvent']})导出类 MyDirective {myEvent:EventEmitter= new EventEmitter();//<----构造函数(){console.log('>>>>>>>>> this.myEvent', this.myEvent);}}

你也可以使用 @HostListener 装饰器:

@Directive({选择器:'[我的指令]'})导出类 MyDirective {@HostListener('myEvent')myEvent:EventEmitter= new EventEmitter();//<-----构造函数(){console.log('>>>>>>>>> this.myEvent', this.myEvent);}}

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

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

解决方案

You need to initialize the output:

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

You could also use the @HostListener decorator:

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

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

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

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