Angular 8: Interaction B/W Child and Parent Component Using Shared Service
Some times we have situation when we need to transfer data from one component to other with no child-parent relation between them. Then…
Angular 8: Interaction Between Two Independent Components Using Shared Service
Some times we have situation when we need to transfer data from one component to other with no child-parent relation between them. Then here comes the idea of Shared Service. We use it when two components are independent of each other . Suppose we have two component
ng g c first-component
ng g c second-component
As we have two components now “First” and “Second” component , we would create s service now usually names “shared” with concept of shared service.
ng g s shared
In our shared service we would initialize an object of EventEmitter() giving it name of your desire I am calling it “event”
export class SharedService {
event = new EventEmitter();
constructor() {}
}
Now you have to emit the event from that component responsible for sending data in this way.
this.sharedService.event.emit(data);
Now subscribe this service where you want to receive data .
this.sharedService.event.subscribe(response => {
//here you can receive data in response
});
If you like my work you can help me in growing through following ways