加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 07:59:08 所属栏目:安全 来源:网络整理
导读:尝试订阅Observable时,我遇到了一个奇怪的错误. 这是代码的淡化版本,它提出了问题: import {Component,Input,OnInit,ViewChild} from '@angular/core';import Rx from 'rxjs/Rx';@Component({ selector: 'action-overview-description',template: require('
尝试订阅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>

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

Invalid event target

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

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

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

问题是你正在使用的生命周期钩子.调用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));

  }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读