netshark1000
netshark1000

Reputation: 7413

Angular: Event Emitter not received

I have a service with an EventEmitter that gets fired if the data changes.

@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?

Upvotes: 0

Views: 1457

Answers (2)

Aakash Jain
Aakash Jain

Reputation: 1973

@Output() and EventEmitter are meant to be used only in components, not in services.

For services, you should use Subject instead.

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

Upvotes: 0

Michał Ochociński
Michał Ochociński

Reputation: 455

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({});
}

Upvotes: 1

Related Questions