Skip to content

Instantly share code, notes, and snippets.

@jotka
Created February 28, 2018 08:08
Show Gist options
  • Select an option

  • Save jotka/75d7495a21564a30723d30e9fef3de61 to your computer and use it in GitHub Desktop.

Select an option

Save jotka/75d7495a21564a30723d30e9fef3de61 to your computer and use it in GitHub Desktop.
Angular 5 events publish - subscribe
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