RxJs中的Subject和Angular2中的EventEmitter

Subject in RxJs and EventEmitter in Angular2

本文关键字:中的 EventEmitter Angular2 Subject RxJs      更新时间:2023-09-26

它们之间有什么区别,何时以及如何使用它们?我读到Subject相当于EventEmitter。

如果我想重写这个,怎么写?

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

EventEmitter s应该只在使用Output装饰器在Angular2组件中实现自定义事件时使用:

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

在其他情况下,你可以使用Subject s(来自Rxjs),因为它与Angular2的特定功能无关。

EventEmitter内部扩展Subject。看到https://github.com/angular/angular/blob/master/modules/%40angular/facade/src/async.ts L63

你的代码看起来不错;-)