What you should use is Subject . If you've ever used an Angular EventEmitter , this is also a Subject . With an EventEmitter we usually use it to publish events from child to parent
@Component({ template: ` <child (textChange)="onTextChange()"></child> ` }) class ParentComponent {} class ChildComponent { @Output() textChange = new EventEmitter(); onClick() { textChange.emit('new value'); } }
That you have ever used this before, this is the publish / subscribe template you need. Someone subscribes to the event, and someone publishes it. Here we can use Subject . Like I said, EventEmitter is a subclass of Subject .
In this case, the Vanilla Subject may not be good enough. The reason is that as soon as an event is emitted, it disappears forever. If no one has signed up, nothing happens to him. So if it happens that you only subscribed to smidget after the event has been issued, then you will not receive anything. Many times this is unacceptable.
In this case, we can use ReplaySubject . This type of object allows you to save a buffer with a custom size. Therefore, if you signed up immediately after the event was released, you will still receive it.
Here is an example
import { ReplaySubject } from 'rxjs/ReplaySubject'; export class SelectedItemService { private _selectedItem = new ReplaySubject<string>(1);
Now the component that wants to publish just needs to set the element
service.selectedItem = 'new item';
And the subscription component
service.selectedItem$.subscribe(item => {})
See also:
UPDATE
See Plunker
source share