Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger notification event in one component and listen in another component in Angular 4 (components do not have parent/child relation)

Tags:

angular

I want to make a change in one component after some activity in another component. The components do not have a parent/child relation. Please tell me the correct solution to this

like image 335
Parita Patel Avatar asked Sep 14 '17 13:09

Parita Patel


1 Answers

you can create a shared service with bi-directional flow using private subjects and public observables. Both the components can subscribe to these observables, where one can push new values and other can react according to the new value changes.

Official docs!

Components in the plunker don't have any parent child relationship.

Working Plunker

 @Injectable()
export class MissionService {

  // Observable string sources
  private missionAnnouncedSource = new Subject<string>();
  private missionConfirmedSource = new Subject<string>();

  // Observable string streams
  missionAnnounced$ = this.missionAnnouncedSource.asObservable();
  missionConfirmed$ = this.missionConfirmedSource.asObservable();

  // Service message commands
  announceMission(mission: string) {
    this.missionAnnouncedSource.next(mission);
  }

  confirmMission(astronaut: string) {
    this.missionConfirmedSource.next(astronaut);
  }
}
like image 195
JayDeeEss Avatar answered Oct 12 '22 23:10

JayDeeEss