【问题标题】:angular2 directive `Cannot read property 'subscribe' of undefined` with outputs metadataangular2指令“无法读取未定义的属性“订阅”,输出元数据
【发布时间】:2016-10-12 10:35:55
【问题描述】:

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

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

【问题讨论】:

    标签: angular angular2-directives


    【解决方案1】:

    你需要初始化输出:

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

    【讨论】:

    • 不客气!事实上,你必须自己初始化它;-)
    • 这仍然适用于 Angular 5.x
    猜你喜欢
    • 2018-01-13
    • 1970-01-01
    • 2021-11-23
    • 1970-01-01
    • 1970-01-01
    • 2019-07-19
    • 2017-05-09
    • 2020-03-07
    • 1970-01-01
    相关资源
    最近更新 更多