[英]Angular: Event Emitter not received
I have a service with an EventEmitter that gets fired if the data changes. 我有一个带有EventEmitter的服务,如果数据更改,该服务会被触发。
@Output() reservationChangedEvent = new EventEmitter<any>();
public notifyReservationsChanged() {
this.reservationChangedEvent.emit({});
}
That the data changes is triggered by a modal that is started from a controller. 数据更改由从控制器启动的模式触发。
In my controller I subscribe for those events: 在我的控制器中,我订阅了这些事件:
ngOnInit() {
...
this.reservationService.reservationChangedEvent.subscribe(() => this.reloadData());
}
My problem is that I can not receive events in my overview component. 我的问题是我无法在概述组件中接收事件。 If I subscribe for events (for checking) in my service or my modal I do receive them.
如果我在我的服务或模态中订阅事件(用于检查),我会收到它们。
Any idea why the overview controller can not receive events? 知道为什么概览控制器无法接收事件吗?
You should change: 您应该更改:
@Output() reservationChangedEvent = new EventEmitter<any>();
to: 至:
reservationChangedSubject = new Subject<any>();
reservationChangedEvent = this.reservationChangedSubject.asObservable()
and this: 和这个:
public notifyReservationsChanged() {
this.reservationChangedEvent.emit({});
}
to: 至:
public notifyReservationsChanged() {
this.reservationChangedSubject.next({});
}
@Output()
and EventEmitter
are meant to be used only in components, not in services. @Output()
和EventEmitter
仅应在组件中使用,而不能在服务中使用。
For services, you should use Subject
instead. 对于服务,您应该改用
Subject
。
Your service should contain: 您的服务应包含:
private reservationChangedSource = new Subject<any>();
reservationChanged$ = this.reservationChangedSource.asObservable();
notifyReservationsChanged() {
this.reservationChangedEvent.next({});
}
In your component: 在您的组件中:
reservationChangeSubscription: Subscription;
ngOnInit() {
...
this.reservationChangeSubscription = this.reservationService.reservationChanged$
.subscribe(() => this.reloadData());
}
ngOnDestroy() {
this.reservationChangeSubscription.unsubscribe();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.