So I have an EventEmitter service that I want to use in order to share data between components, here is the code
import { Injectable, EventEmitter } from '@angular/core';
@Injectable()
export class ObservableService {
data = [];
eventEmitter: EventEmitter<any> = new EventEmitter();
setSharedData(key, value) {
this.data[key] = value;
this.eventEmitter.emit(this.data);
}
getSharedData() {
return this.data;
}
}
And here is how I want to use it
ngOnInit() {
this._observable.eventEmitter.subscribe((data) => {
console.log('working');
this.filter.emit(data);
})
}
So, everything works perfect except one thing - console log showing working
sign 13 times!
Where this strange behavior goes from?
EventEmitter
are used to raise custom events from directive or component. Its not advisable to use it insideservice
as you have used.You should use
Observable
inside your service so that you cansubscribe
for it inside yourComponent
.Check Parent and children communicate via a service to know how to use
Observable
.