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

What is preventing form validation from functioning properly with both built-in and cross-field validators?

I've been facing issues while trying to develop a form with built-in validators and cross-field validator. Unfortunately, the functionality is not working as expected and I'm struggling to understand why. The form should contain four types of bu ...

"Encountering a problem when trying to display Swagger-Editor for the second

While integrating the swagger-editor package into my React application, I encountered an issue. The first time I fetch the Swagger specifications from GitHub, everything works perfectly and validates correctly. However, upon rendering it a second time, an ...

Unable to direct XHR requests even though the URL is functional in the browser

I am currently working on developing a REST API in TypeScript using NodeJS and Express. So far, the API is up and running on localhost. When I visit http://localhost:8080, everything functions as expected. Specifically, I have configured the route http:/ ...

Issues with Angular ChartJS where the minimum value for scales and callback functions are not functioning as

I am encountering an issue while using ChartJS line chart in my Angular 9 application. I am attempting to adjust the Y axes of my chart so that they start from 0 (instead of the minimum value) and include a '%' symbol after each value. Below is a ...

Incorporate the angular-cdk table functionality seamlessly with the sleek design of Bootstrap

Looking to enhance the design of my Angular application by incorporating Bootstrap table styling with the use of Angular CDK table (without Angular Material2). One challenge I've encountered is that while it's possible to add classes to the CDK ...

Copy and paste the code from your clipboard into various input fields

I have been searching for a Vanilla JavaScript solution to copy and paste code into multiple input fields. Although I have found solutions on the internet, they are all jQuery-based. Here is an example of such a jQuery solution <input type="text" maxl ...

Dynamically altering the CSS4 variables in real time

I am facing the challenge of managing multiple CSS4 variables, including primary, for various companies. How can I dynamically change the primary CSS4 variable color based on the company? Note: My specific requirement is to update the primary variable glo ...

Matching the types of method parameters to the types of callback function parameters in Typescript generics

I am currently working on creating a class that takes a function as a parameter in the constructor. The function can have arguments of any type. My goal is to add a method to the class that also accepts the same arguments as the function parameter, essenti ...

Array containing HTML code for Ionic framework

Just starting out with Ionic/Angular and I have a question. How can I display an array containing HTML content? { "code" : "06", "descr" : "Some text:</br>Other text.<br/>Other text</br>Other text." } When I try to print it, the HTML ta ...

Navigating to a Different Page in Angular 7

After logging in on my login page, the dashboard component appears below the login page instead of redirecting as a new page. How can I achieve this in Angular 7? Any assistance would be greatly appreciated. Thank you! app.component.ts import { Component ...

Tips for managing Razorpay responses in Angular 2

I'm currently in the process of finalizing my payment transaction through RazorPay Payment gateway, and I've attempted to do so as shown below: var options = { "key": "XXX", "amount": 100, "name": "Ezshipp", "description": this.it ...

Error in Ionic Cordova Build prod: Module "." not found - Requires Typescript version >3

After updating my ionic project and all dependencies, I encountered an error when trying to build a --prod android apk: Uncaught Error: Cannot find module "." at vendor.js:1 at vendor.js:1 at Object.<anonymous> (vendor.js:1) at e (vendor.js:1) at Ob ...

Searching for a streamlined approach to retrieve a segment of a string

I'm currently working with JavaScript and TypeScript. Within my code, I encountered a scenario where I have a string that might contain certain tags indicating importance or urgency. Here are a couple of examples: A: "Remind me to go to the store to ...

Make sure to include the @ symbol before "angular" in the package.json file when setting

Can someone explain to me why the Angular 2 quickstart guide suggests using a package.json file structured like this: { "name": "angular2-quickstart", "version": "1.0.0", "scripts": { "start": "tsc && concurrently \"npm run tsc:w&bs ...

Filtering incoming data from a Firestore database: A step-by-step guide

I'm facing a challenge while trying to incorporate this filtering mechanism into my code. FILTERING An issue arises when I attempt to implement the following lines of code: function search(text: string, pipe: PipeTransform): Country[] { return CO ...

Strategies for Creating a Test Suite for RepositoryFactory in Vue.js/Nuxt.js

Summary of RepositoryFactory Implementation An implementation of the RepositoryFactory pattern has been carried out for API connection in a Vue.js/Nuxt.js application. For more details, refer to this article: here hogeRepository.ts import { NuxtAxiosInst ...

What is the proper way to manage errors caught in the ngrx effect's catch block and store them in the component?

I am seeking advice on how to manage the scenario when data loading fails in my component. I would like to know if it is preferable to include selectors for error handling or address it within effects. My experience with ngrx and fetching data through ac ...

Decoding the mysteries of a ZoneAwareError: A guide to unraveling the enigma

Within my Angular 2 application, I utilize a resolve guard that performs an XHR request and throws a custom error if the request fails: return this.service.getProduct (id) .catch (err => Observable.throw(new MyError(err.message, route, 500, err))); ...

Challenge with React CloneElement regarding typing

Utilizing React Children and React Clone element, I aim to trigger methods in both the wrapper and Select components upon onClick event in the Option component. Although everything is functioning correctly, I am encountering a type error when calling the O ...

Switching between different types of generic functions in typescript

Is there a way to convert between these two types of generic functions: type Foo=<S>(a: S) => S type FooReturnType = ReturnType<Foo> // unknown type Bar<S> = { (a: S): S } type BarReturnType = ReturnType<Bar<string> ...