Skip to content

Instantly share code, notes, and snippets.

@gabrielqmatos88
Created January 30, 2020 18:12
Show Gist options
  • Save gabrielqmatos88/3a93199de8ae4ab389b39541cf3cff03 to your computer and use it in GitHub Desktop.
Save gabrielqmatos88/3a93199de8ae4ab389b39541cf3cff03 to your computer and use it in GitHub Desktop.
Angular components communication using service
import { Component, OnInit } from '@angular/core';
import { NotificationService } from './notification.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class Exemplo1Component implements OnInit {
ngOnInit() {
NotificationService.get('evento_fake').subscribe( (eventData) => {
const { comp, data} = eventData;
console.log(`qual componente? ${comp} - data: ${data} `);
});
}
operacaoFake() {
NotificationService.emit('evento_fake', {
comp: 'exemplo1',
data: 'whatever you want send goes here'
});
}
}
import { Component, OnInit } from '@angular/core';
import { NotificationService } from './notification.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class Exemplo2Component implements OnInit {
ngOnInit() {
NotificationService.get('evento_fake').subscribe( (eventData) => {
const { comp, data} = eventData;
console.log(`qual componente? ${comp} - data: ${data} `);
});
}
operacaoFake() {
NotificationService.emit('evento_fake', {
comp: 'exemplo2',
data: {
test1: 'test1'
val: 50;
}
});
}
}
import { Injectable, EventEmitter } from '@angular/core';
/**
* Notification service
* Used to provide communication between components or services
*/
@Injectable()
export class NotificationService {
/**
* Declare and initializes the emitter object
*/
private static emitters: { [eventName: string]: EventEmitter<any> } = {};
/**
* Gets notification service
* @param eventName name of event to subscribe
* @returns the event emitter
*/
static get(eventName: string): EventEmitter<any> {
if (!this.emitters[eventName]) {
this.emitters[eventName] = new EventEmitter<any>();
}
return this.emitters[eventName];
}
/**
* Emits notification service
* @param eventName name of event to be fired
* @param data event data content
*/
static emit(eventName: string, data: any): void {
NotificationService.get(eventName).emit(data);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment