这个错误通常是因为在使用 fromEvent 时未正确订阅或反订阅函数。
例如,假设我们有一个按钮,我们想要在点击它时触发一个事件。我们可以使用以下代码在组件中订阅点击事件:
import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { fromEvent } from 'rxjs';
@Component({
selector: 'app-example',
template: '',
})
export class ExampleComponent implements OnInit {
@ViewChild('btn') button: ElementRef;
ngOnInit() {
fromEvent(this.button.nativeElement, 'click').subscribe(() => {
console.log('Button clicked');
});
}
}
但是,如果我们在订阅点击事件之前,按钮尚未初始化,那么当代码尝试读取 nativeElement 属性时,就会触发上述错误。
为了解决这个错误,我们可以在组件的 ngAfterViewInit 函数中订阅点击事件,这样按钮就保证已初始化:
import { Component, ElementRef, AfterViewInit, ViewChild } from '@angular/core';
import { fromEvent } from 'rxjs';
@Component({
selector: 'app-example',
template: '',
})
export class ExampleComponent implements AfterViewInit {
@ViewChild('btn') button: ElementRef;
ngAfterViewInit() {
fromEvent(this.button.nativeElement, 'click').subscribe(() => {
console.log('Button clicked');
});
}
}