dea*_*git 18 observable rxjs angular
尝试订阅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));
}
}Run Code Online (Sandbox Code Playgroud)
<button #input>Button</button>Run Code Online (Sandbox Code Playgroud)
我在控制台中遇到的错误是:
无效的事件目标
当我订阅流时,错误仅显示.如果我只创建它但不订阅,则没有错误.如果我在console.log中流,它似乎有一个订阅成员.
我试过谷歌搜索错误,但我似乎无法找到它解释的任何地方.
我想我正在使用Rxjs 4.0.5(根据npm rxjs --version).
Ang*_*hef 44
问题是你正在使用的生命周期钩子.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));
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
28637 次 |
| 最近记录: |