[英]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. 我读到Subject等同于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);
}
}
EventEmitter
s should be used only when implementing custom events in Angular2 components with the Output
decorator: EventEmitter
实现与Angular2组件自定义事件,当s只应该用于Output
装饰:
@Output()
someEvent: EventEmitter = new EventEmitter();
In other cases, you can use Subject
s (from Rxjs) since it's not related to Angular2 particular feature. 在其他情况下,您可以使用Subject
(来自Rxjs),因为它与Angular2特定功能无关。
EventEmitter
internally extends Subject
. EventEmitter
内部扩展了Subject
。 See https://github.com/angular/angular/blob/master/modules/%40angular/facade/src/async.ts#L63 请参阅https://github.com/angular/angular/blob/master/modules/%40angular/facade/src/async.ts#L63
Your code looks good to me ;-) 你的代码对我来说很好;-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.