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

问题描述 投票:0回答:3

尝试订阅 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)。

angular rxjs observable
3个回答
64
投票

问题在于您正在使用的生命周期挂钩。当调用

ngOnInit
时,该元素尚未在 DOM 中创建。相反,您应该使用
ngAfterViewInit

您可以尝试以下代码吗:

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

  }
}

2
投票

如果你想在

ngOnInit
事件中访问它,那么你必须使用
{ static: true }
ViewChild
属性,如下所示:

import { Component, ViewChild, ElementRef, OnInit } from '@angular/core';
import { Observable, fromEvent } from 'rxjs';

@Component({
  template: '<button #input>Button</button>'
})
export class ActionOverviewDescription implements OnInit {
  @ViewChild('input', { static: true }) button: ElementRef;

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

  }
}

0
投票

现有的解决方案都无法解决我的问题,所以我找到了另一个解决方案:

{ read: ElementRef }
添加到
@ViewChild
装饰器。以下是我的具体代码:

 @ViewChild('saveButton', { static: true, read: ElementRef }) saveButton: ElementRef;

即使没有

{ static: true }
部分,它也能工作:

 @ViewChild('saveButton', { read: ElementRef }) saveButton: ElementRef;

这是我使用按钮的地方:

 ngAfterViewInit() {
    fromEvent(this.saveButton.nativeElement, 'click')
      .pipe(
         concatMap(() => this.saveCourse(this.form.value))
    ).subscribe();
 }

来源:https://forum.ionicframework.com/t/v4-fromevent-rxjs-error-typeerror-invalid-event-target/151000

© www.soinside.com 2019 - 2024. All rights reserved.