它们之间有什么区别,何时以及如何使用它们?我读到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);
}
}
答案 0 :(得分:4)
EventEmitter
装饰器在Angular2组件中实现自定义事件时,才应使用 Output
:
@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
您的代码对我来说很好; - )