Broadcasting events across the entire system

I'm trying to accomplish something specific in Angular2 - emitting a custom event globally and having multiple components listen to it, not just following the parent-child pattern.

Within my event source component, I have:

export class EventSourceComponent{

  @Output() testev = new EventEmitter();

  onbtnclick(){
    this.testev.emit("I have emitted an event")
  }
 }

Now, I want other components to receive this event:

export class CmpTwoComponent{

    //Receive the emitted event with data here
  } 

How can I achieve the above?

Answer №1

Utilizing a shared service for this task would be ideal.

export class EventSourceComponent{
    constructor(private sharedService : SharedService){}


      onbtnclick(){
        this.sharedService.testev.next("i have emitted an event")
      }
 }

export class CmpTwoComponent{

//receiving the emitted event with data

   constructor(sharedService : SharedService){

      sharedService.testev.subscribe((event)=>{console.log(event)})
   }

} 

The implementation of the sharedService would look like:

@Injectable()
export class SharedService{

   public testev = new Subject()

}

If you still require the use of Output for the parent component to subscribe normally, it can also be added in the following way:

export class EventSourceComponent{

    @Output() testev = new EventEmitter();
    constructor(private sharedService : SharedService){}

      onbtnclick(){
        this.testev.emit("i have emitted an event")
        this.sharedService.testev.next("i have emitted an event")
      }
 }

Answer №2

Unfortunately, Angular does not have a built-in pattern that can fulfill your requirements.

One possible solution would be to develop a custom service. This service can be injected into AppComponent to ensure there is only one instance. Within the service, you can implement any desired logic.

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

Error deploying to Heroku: Unable to obtain access

I've been working on deploying my MEAN application to Heroku, and while the deployment is successful, I'm encountering an error when trying to open the application - it keeps showing a "CANNOT / GET" message. Upon checking the console, I see the ...

Different return types of a function in Typescript when the parameter is either undefined or its type is explicitly asserted vary

Addressing Complexity This code may seem simple, but the use case it serves is quite complex: type CustomFunction = <B extends ['A']>( param?: B ) => B extends undefined ? 'TYPE_1' : 'TYPE_2' // Usage examples: co ...

Accessing HTTP data through a function instead of using ngOnInit in Angular is a more efficient approach

Trying to retrieve data from a service using setInterval has posed an issue for me. When I call the service from ngOnInit, everything functions as expected. However, when attempting to call it from any other function, an error occurs: "ERROR TypeError: Ca ...

How can Angular CLI prevent the submission of an HTML form unless a previous option has been selected

I am currently working on a form that contains select fields with various options pre-populated. <form [formGroup]="selectVehicleForm"> <select formControlName="Manufacturer"> <option *ngFor='let ...

Set up Admin SDK using appropriate credentials for the given environment

As someone new to Node.js, Firebase Cloud Functions, and TypeScript, my objective is to create a cloud function that acts as an HTTP endpoint for clients to authenticate with Firebase. The desired outcome is for the cloud function to provide a custom acces ...

Access another key within an object

Here's a code snippet from my module: exports.yeah = { hallo: { shine: "was", yum: this.hallo.shine } } In the above code, I'm attempting to reference the shine property in yum: this.hallo.shine However, when I run the script, ...

Can the Route be modified in Next.js?

I have developed search functionality that navigates to "/search/xxxx", but it is located in the header. Every time I perform a search, the route gets repeated and becomes "/search/search/xxx". Could you suggest any way other than usin ...

Using jQuery to send LocalStorage data to an email address with the help of PHP

Currently, I am in the process of developing a basic eCommerce/checkout system. My goal is to utilize localStorage data and transfer it to PHP using jQuery or any other method that is convenient. However, when I attempted to send the email, I only received ...

How do I go about showing every character on a separate line using a for loop?

var input = prompt("What is Lance attempting to convey?"); //user enters any text for (var i = 0; i <= input.length; i++) { var output = input.charAt(i); if (output == "e" || output == "o" || output == "a" || output == "u") { outp ...

What is the method for retrieving a temporary collection in a callback function when using node-mongodb-native find()?

Is it possible to retrieve a temporary collection from a find() operation instead of just a cursor in node-mongodb-native? I need to perform a mapReduce function on the results of the find() query, like this: client.open(function(err) { client.collect ...

Using string interpolation within the innerHTML property in Angular 2

How do I render an expression using the [innerHTML] directive? public stringInterpolation: string = 'title'; public data: any = '<a>{{stringInterpolation}}</a>'; <div [innerHTML]="data"></div> The issue is th ...

Transmit information from an Angular 2 client to a Spring server using a POST request

I'm encountering an issue where the data is null on the server side even though there are no errors. Can someone provide me with an example to help resolve this? Thank you. Here is my client service: import {Injectable, Inject} from "angular2/core"; ...

Set a variable to represent a color for the background styling in CSS

My goal is to create an application that allows users to change the background color of a button and then copy the CSS code with the new background color from the <style> tags. To achieve this, I am utilizing a color picker tool from . I believe I ...

Is there a way to customize the color of an element within CardHeader in MUI?

Is there a way to customize the colors of {note.title} and {note.category}? I have attempted to do so by creating a theme: const theme = createTheme ({ palette: { category: { color: blue } } }) Unfortunately, this appro ...

Exploring the process of implementing smooth transitions when toggling between light and dark modes using JavaScript

var container = document.querySelector(".container") var light2 = document.getElementById("light"); var dark2 = document.getElementById("dark"); light2.addEventListener('click', lightMode); function lightMode(){ contai ...

React.js issue with onChange event on <input> element freezing

I am experiencing an issue where the input box only allows me to type one letter at a time before getting stuck in its original position. This behavior is confusing to me as the code works fine in another project of mine. const [name, setName] = useStat ...

Array vs Single Object - Comparing AngularJS / Javascript Data Structures (Basic)

My array is very basic [ { ticketId: 1, name: "John", }, { ticketId: 124, name: "Ads" } ] I have displayed the data in a dropdown menu <ul class="dropdown-menu"> <li ng-repeat="ticket in tickets"> <a h ...

The sweetalert 2 input field is unresponsive or disabled within a materializecss modal, making it impossible to type in

My modal includes a SweetAlert2 popup when I click the "add bills" button. The code for this feature is from their documentation, so I don't believe the issue lies there. However, I am experiencing a problem where the input field is not type-able and ...

Currently in the process of configuring an ionic project, encountering a series of errors upon executing the npm install command

gyp ERR! configure error gyp ERR! stack Error: Unable to locate Python executable "python", please set the PYTHON environment variable. gyp ERR! stack at PythonFinder.failNoPython (C:\Program Files\nodejs\node_modules\npm\node_ ...

What is the best way to trigger an onclick event for an input element with a type of "image"?

In the code I'm working on, there's an input of type "Image". <div class="icon" id="button_dictionary"> <form> <input class="buttonDictionary" type="image" src="icone_dicionario.jpg" value="" id="inputDictionary"> ...