The easiest way to understand this is to think about Subject as both a producer and a consumer. It is like an open channel where someone can send a message at one end, and all subscribers will receive it at the other end.
+--------------- Sender | => => => => Subscriber -----------------------+ +----------- Message => => => => => => => => => => => Subscriber -----------------------+ +----------- | => => => => Subscriber +---------------
The text terms say that you have a service with a subject
class MessageService { private _messages = new Subject<Message>(); get messages: Observable<Message> { return this._messages.asObservable(); } sendMessage(message: Message) { this._messages.next(message); } }
Note that the receiver of messages returns the object as observable. This is not required. Subject already observable, and anyone can subscribe directly to Subject . But I think that the asObservable template asObservable used as a way to limit what users can do with it, that is, users use it only for subscription, and not for emitting. We save radiation for the sendMessage method.
Now with this service we can implement it in different components, and this may be a way for two (or more) arbitrary components to communicate (or just to receive arbitrary event notifications).
class ComponentOne { constructor(private messages: MessageService) {} onClick() { this.messages.sendMessage(new Message(..)); } } class ComponentTwo { constructor(private messages: MessageService) {} ngOnInit() { this.messages.messages.subscribe((message: Message) => { this.message = message; }); } }
The corner own EventEmitter is actually a Subject . When we join an EventEmitter , we subscribe to a Subject , and when we emit to an EventEmitter , we send a message through Subject to all subscribers.
See also:
source share