Created
February 28, 2018 08:08
-
-
Save jotka/75d7495a21564a30723d30e9fef3de61 to your computer and use it in GitHub Desktop.
Angular 5 events publish - subscribe
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| export class MyServiceEvent { | |
| message: string; | |
| eventId: number; | |
| } | |
| export class MyService { | |
| public onChange: EventEmitter<MyServiceEvent> = new EventEmitter<MyServiceEvent>(); | |
| public doSomething(message: string) { | |
| // do something, then... | |
| this.onChange.emit({message: message, eventId: 42}); | |
| } | |
| } | |
| export class MyConsumer { | |
| private _serviceSubscription; | |
| constructor(private service: MyService) { | |
| this._serviceSubscription = this.service.onChange.subscribe({ | |
| next: (event: MyServiceEvent) => { | |
| console.log(`Received message #${event.eventId}: ${event.message}`); | |
| } | |
| }) | |
| } | |
| public consume() { | |
| // do some stuff, then later... | |
| this.cleanup(); | |
| } | |
| private cleanup() { | |
| this._serviceSubscription.unsubscribe(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment