Xinrui Ma
Xinrui Ma

Reputation: 2105

Subject in RxJs and EventEmitter in Angular2

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

Upvotes: 3

Views: 1398

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202296

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

Upvotes: 4

Related Questions