What is the process for listening to custom events in Angular 4 components that have been loaded using routing?

In the app.component.html file

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

When we route to the DisplayAllStatsComponent, how can we listen for the 'viewdetails' event triggered in the above li or a tag? In the app.module.ts file

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

In the DisplayAllStatsComponent, when the component is clicked it triggers an event

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

// The function below is called here.

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

Now I need the emitted value in the app.component.html file

Answer №1

The EventEmitter is typically used to facilitate communication between parent and child components, but in your specific case, it may not yield the desired result. However, there is an alternative method to effectively "broadcast" an event by utilizing a Subject.

To achieve this, you can establish a Broadcaster class similar to the following implementation:

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;
}

You can then broadcast the event as demonstrated below:

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

To receive the broadcasted event in your app component, subscribe to it like so:

this.broadcaster.on$("viewDetailsEvent").subscribe(viewDetails => {
  // Implement your custom logic using the received viewDetails data
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing TypeScript with Context API

This is my first time working with Typescript to create a context, and I'm struggling to get it functioning properly. Whenever I try to define interfaces and include them in my value prop, I encounter errors that I can't figure out on my own. Spe ...

What is the best way to capture the inputs' values and store them accurately in my object within localStorage?

Is there a more efficient way to get all the input values ​​and place them in the appropriate location in my object (localStorage) without having to individually retrieve them as shown in the code below? Below is the function I currently use to update ...

The issue of Angular 15 Childcomponent failing to refresh the user interface despite input modifications

Within this component, I have two child components: <span>Timings:</span> <sir-project-fasetiming [faseTiming]="projectTiming.timingInitiatie" (faseTimingChanged)="faseTimingChanged($event, 'timingInitiatie')"&g ...

Issues with implementing AddEventListener in InAppBrowser on IONIC 2

I am currently working on implementing AddeventListener to listen for 'Exit' and 'LoadStart' events in InAppBrowser within IONIC2. Here is my HTML: <button (click)="browsersystem('https://www.google.com')" > Visit URL& ...

Ways to make the input field appear invalid without the use of forms, causing the bottom outline to turn red when a specific condition is met

Currently, the application does not utilize any forms. I am interested in making the input field invalid under certain conditions within the component. For example, if a user leaves the input field blank, I would like the bottom outline to turn red when an ...

Unable to organize the data associated with a specific column in the header within an Angular material Table

viewing clinical history data the output I'm receiving is not in ascending or descending order Trying to organize the data in the table, utilizing the MatTableModule module alongside other required modules. However, after conducting research, I have ...

Display only the clear button within the p-calendar element

I am struggling to make a Clear button appear only on the p-calendar component. myComponent.html <p-calendar value="#{property.propDate}" id="date" [showIcon]="true" [utc]='true' placeholder="{{ timePickerPlaceHolder }}" [showTrans ...

What is the best way to retrieve data from a server and display it using Highcharts in Angular 2

This is my chart component and I am trying to display a chart with values from the server. Unfortunately, it's not working even though it works with static values. In the ngOnInit method, I call the web service and store the data in a variable called ...

The access to the HTTP response object is not possible: the property is not found on the Object type

I recently created a response object and assigned it to the "this" object. However, when I try to access the datacentersinfo property, I encounter an error stating that the property does not exist on type Object. Due to this issue, I am unable to generat ...

Steps to resolve the issue of being unable to destructure property temperatureData from 'undefined' or 'null' in a React application without using a class component

CODE: const { temperatureData } = state; return ( <> <div className="flex flex-row"> {temperatureData.map((item, i) => ( <div className="flex flex-auto rounded justify-center items-center te ...

How to effectively manage errors in TypeScript using RxJS?

Exploring subscribe arguments in the official RxJS documentation has raised some interesting questions for me. For instance, what is the purpose of using error: (e: string) => { ... } to catch errors emitted by an observable? Despite this implementation ...

Why does the method of type assigning vary between actual and generic types?

There are no errors in the code shown below: type C = {b: string}; class Class { data: C; constructor(data: C) { this.data = data; } test() { const hack: C & {a?: any} = this.data; //no error } } However, when a g ...

Angular 4's Mddialog experiencing intermittent display problem

While using MDDialog in my Angular app, I've encountered a couple of issues. Whenever a user clicks on the div, flickering occurs. Additionally, if the user then clicks on one of the buttons, the afterclose event is not triggered. Can anyone provide ...

Best practices for extending the Array<T> in typescript

In a discussion on extending the Static String Class in Typescript, I came across an example showing how we can extend existing base classes in typescript by adding new methods. interface StringConstructor { isNullOrEmpty(str:string):boolean; } String. ...

Eliminate the need for 'any' in TypeScript code by utilizing generics and partials to bind two parameters

I'm working with TypeScript and have the following code snippet: type SportJournal = { type: 'S', sport: boolean, id: string} type ArtJournal = { type: 'A', art: boolean, id: string} type Journal = SportJournal | ArtJournal; type J ...

Having trouble resolving the error "Cannot find name CSSTranslate" while working with VSCode and tsc? Let's tackle this issue together

My program runs smoothly in a development environment and appears flawless in VSCode, but I'm encountering issues with tsc pointing out unknown names and properties. It's puzzling because my file doesn't seem to have any problems in VSCode. ...

The dynamic change in the maximum value of the Ngb rating is not being accurately displayed in the length of the

The dynamic change in the maximum value of ngb rating is not being reflected in the length of the stars. Although two-way binding occurs with [max]="", the length of the stars remains unchanged. <ngb-rating [(rate)]="currentRate" [ma ...

Issue with Socket.io: Data not received by the last user who connected

I have developed a Node.js and Express application with real-time drawing functionality on canvas using socket.io version 1.7.2. Users are divided into separate socket rooms to enable multiple teams to draw independently. However, there is an issue where t ...

Nest faces difficulty resolving the dependencies required by the TMPController

I've tried everything to fix this error, but nothing seems to be working. tmp.module.ts import { Module } from "@nestjs/common"; import { TMPController } from "./tmp.controller"; import { TMPService } from "./tmp.service"; @Module({ controllers: ...

Troubleshooting AngularJS2 and npm in WebStorm and Chrome for Windows users

Having completed the official Hero tutorial for AngularJs2 using Visual Studio Code, I decided to switch my coding and debugging setup to WebStorm+Chrome on Windows 10. To achieve this transition, I took the following steps: Installed Chrome JetBrains ...