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

前端之家收集整理的这篇文章主要介绍了Angular 2 – 订阅Observable.fromEvent错误:“无效的事件目标”前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
尝试订阅Observable时,我遇到了一个奇怪的错误.

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

@H_403_3@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)); } } @H_403_3@<button #input>Button</button>

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

Invalid event target

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

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

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

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

你能尝试下面的代码

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

猜你在找的Angularjs相关文章