3

What's the difference between them, when and how to use them? I read that Subject is the equivalent to an EventEmitter.

If I want to rewrite this, how?

import { Injectable} from '@angular/core';
import { Subject,BehaviorSubject } from 'rxjs';
import {Playlists} from 'channel' /** Assumes this is where you have defined your Playlists interface **/

@Injectable()
export class PlaylistService {
    private _currentPlaylists$: Subject<Playlists> = new BehaviorSubject<Playlists>(null);
    constructor() {}

    currentPlaylists() {
      return this._currentPlaylists$.asObservable();
    }

    setCurrentPlaylists(playlists:Playlists){
      this._currentPlaylists$.next(playlists);
    }
}
Xinrui Ma
  • 2,065
  • 5
  • 30
  • 52
  • See http://stackoverflow.com/questions/36076700/what-is-the-proper-use-of-an-eventemitter for the proper use of EventEmitter. – Mark Rajcok Aug 11 '16 at 17:29

1 Answers1

4

EventEmitters should be used only when implementing custom events in Angular2 components with the Output decorator:

@Output()
someEvent: EventEmitter = new EventEmitter();

In other cases, you can use Subjects (from Rxjs) since it's not related to Angular2 particular feature.

EventEmitter internally extends Subject. See https://github.com/angular/angular/blob/master/modules/%40angular/facade/src/async.ts#L63

Your code looks good to me ;-)

Thierry Templier
  • 198,364
  • 44
  • 396
  • 360