Search code examples
angulareventemitter

Angular2: EventEmitter based service too many calls


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?


Solution

  • EventEmitter are used to raise custom events from directive or component. Its not advisable to use it inside service as you have used.

    You should use Observable inside your service so that you can subscribe for it inside your Component.

    Check Parent and children communicate via a service to know how to use Observable.