在 Angular 12 中,EventEmitter 类已被弃用,因此可能会出现“Event emitter is undefined”错误。解决此问题的解决方案是使用 RxJS 的 Subject 来实现事件传递。
例如,在组件中声明一个名为“dataUpdated”的新 Subject:
import { Subject } from 'rxjs';
export class MyComponent { dataUpdated = new Subject();
// other component code... }
然后,在可能导致事件发生的组件方法中发送事件:
this.dataUpdated.next();
最后,在订阅组件中,使用 Subject 的相应方法来订阅事件:
import { Component, OnInit } from '@angular/core'; import { MyComponent } from '../my.component';
@Component({
selector: 'app-subscribe-component',
template: Subscribed Value: {{ subscribedValue }}
})
export class SubscribeComponent implements OnInit {
subscribedValue: any;
constructor(private myComponent: MyComponent) { }
ngOnInit() { this.myComponent.dataUpdated.subscribe((value) => { this.subscribedValue = value; }); } }
这样,你就可以使用 RxJS 的 Subject 实现 Angular 应用中的事件传递,避免出现“Event emitter is undefined”错误。