首页 文章

Angular 2 - 订阅Observable.fromEvent错误:“无效的事件目标”

提问于
浏览
13

尝试订阅Observable时,我遇到了一个奇怪的错误 .

这是代码的淡化版本,它提出了问题:

import {Component, Input, OnInit, ViewChild} from '@angular/core';
import Rx from 'rxjs/Rx';

@Component({
  selector: 'action-overview-description',
  template: require('./actionOverviewDescription.html')
})
export class ActionOverviewDescription  {
  @ViewChild('button') button;

  constructor() {}
  
   ngOnInit() {

    let buttonStream$ = Rx.Observable.fromEvent(this.button, 'click')
        .subscribe(res => console.log(res));

  }
}
<button #input>Button</button>

我在控制台中遇到的错误是:

无效的事件目标

当我订阅流时,错误仅显示 . 如果我只创建它但不订阅,则没有错误 . 如果我在console.log中流,它似乎有一个订阅成员 .

我试过谷歌搜索错误,但我似乎无法找到它解释的任何地方 .

我想我正在使用Rxjs 4.0.5(根据npm rxjs --version) .

1 回答

  • 35

    问题是你正在使用的生命周期钩子 . 调用 ngOnInit 时,该元素尚未在DOM中创建 . 相反,你应该使用 ngAfterViewInit .

    你能尝试下面的代码:

    import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
    import { Observable } from 'rxjs/Observable';
    import 'rxjs/add/observable/fromEvent';
    
    @Component({
      template: '<button #input>Button</button>'
    })
    export class ActionOverviewDescription implements AfterViewInit {
      @ViewChild('input') button: ElementRef;
    
      ngAfterViewInit() {
        let buttonStream$ = Observable.fromEvent(this.button.nativeElement, 'click')
            .subscribe(res => console.log(res));
    
      }
    }
    

相关问题