Angular 2 - 订阅 Observable.fromEvent 错误:“无效的事件目标" [英] Angular 2 - subscribing to Observable.fromEvent error: "Invalid event target"
问题描述
我在尝试订阅 Observable 时遇到一个奇怪的错误.
I am getting a weird error when trying to subscribe to an Observable.
这里是出现问题的代码的淡化版本:
Here is a watered down version of the code which presents the problem:
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>
我在控制台中得到的错误是:
The error I get in the console is:
无效的事件目标
错误仅在我订阅流时出现.如果我只创建它但不订阅,则没有错误.如果我 console.log 流它似乎有一个订阅成员.
The error ONLY shows up when I subscribe to the stream. If I only create it but don't subscribe, there is no error. If I console.log the stream it seems to have a subscribe member.
我尝试在谷歌上搜索错误,但似乎找不到任何解释它的地方.
I have tried googling the error but I can't seem to find anywhere it's explained.
我想我使用的是 Rxjs 4.0.5(根据 npm rxjs --version).
I think I'm using Rxjs 4.0.5 (according to npm rxjs --version).
推荐答案
问题在于您使用的生命周期挂钩.当 ngOnInit
被调用时,元素还没有在 DOM 中创建.相反,您应该使用 ngAfterViewInit
.
The problem is the lifecycle hook you're using. The element is not yet creating in DOM when ngOnInit
is called. Instead, you should use ngAfterViewInit
.
你能不能试试下面的代码:
Could you try the following code:
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
import { Observable, fromEvent } from 'rxjs';
@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));
}
}
这篇关于Angular 2 - 订阅 Observable.fromEvent 错误:“无效的事件目标"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!