1

In app.component.html

<li routerLinkActive="active current">
       <a  [routerLink]="['/stats']">
                    Cluster stats
       </a>
   </li>

Since we are routing to DisplayAllStatsComponent , how to listen for 'viewdetails' event triggered in above li or a tag? In app.module.ts

{ 
    path:'/stats', 
    component : DisplayAllStatsComponent
 }

In DisplayAllStatsComponent when the component is clicked it triggers an event

@Output('viewdetails') viewdetails = new EventEmitter();

// here below function is called .

  callViewDetails(name,alias){
    let ev = {
      name:name,alias:alias
    };
    this.viewdetails.emit(ev); // here value is being emitted.
  }

now i need the emitted value in app.component.html

JackAss
  • 338
  • 1
  • 4
  • 17

1 Answers1

1

The EventEmitter can be used to communicate between parent and child components. In your case, it won't work. However, there is a way to "broadcast" an event using a Subject.

You can create a Broadcaster class, which would be something like this:

import { Subject } from "rxjs/Subject";
import { Observable } from "rxjs/Observable";
import "rxjs/add/operator/filter";
import "rxjs/add/operator/map";

export class Broadcaster {
  private _event: Subject<BroadcastEvent>;

  constructor() {
    this._event = new Subject<BroadcastEvent>();
  }

  broadcast$(key: any, data?: any) {
    this._event.next({key, data});
  }

  on$<T>(key: any): Observable<T> {
    return this._event.asObservable()
      .filter(event => event.key === key)
      .map(event => <T>event.data);
  }
}

export interface BroadcastEvent {
  key: any;
  data?: any;
}

Then, you can broadcast the event like this:

callViewDetails(name,alias){
    let ev = {
      name:name,alias:alias
    };
    this.broadcaster.broadcast$("viewDetailsEvent", ev); //Broadcast
  }

And subscribe to the event in your app component:

this.broadcaster.on$("viewDetailsEvent").subscribe(viewDetails => {
  //do whatever you want with the viewDetails here
})
DGarvanski
  • 2,555
  • 3
  • 26
  • 35