Angular2: EventEmitter based service too many calls

1.1k views Asked by At

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?

2

There are 2 answers

0
ranakrunal9 On BEST ANSWER

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.

0
love prince On

EventEmitter do not function. I think you should use @Output with EventEmitter:

import { Injectable, EventEmitter, Output } from '@angular/core';

@Injectable()
@Component({
selector: 'sector'
})
export class ObservableService {
    data = [];
    @Output eventEmitter: EventEmitter<any> = new EventEmitter();

    setSharedData(key, value) {
        this.data[key] = value;
        this.eventEmitter.emit(this.data);
    }

    getSharedData() {
        return this.data;
    }
}

and HTML

   <sector (eventEmitter)="_eventEmitter" ></sector>

component

 _eventEmitter: any;
 ngOnInit() {
        this.filter = this._eventEmitter;
    }