Angular 6 / Typescript broadcasting event tutorial

In my code, I've structured it as follows:

<app>
  <test-a></test-a>
  <test-b></test-b>
</app>

@Component({
    selector: 'app',
    templateUrl: './app.component.html',
})
export class AppComponent {
}    

@Component({
    selector: 'test-a',
    templateUrl: './testa.component.html',
})
export class TestAComponent {
}

@Component({
    selector: 'test-b',
    templateUrl: './testb.component.html',
})
export class TestBComponent {
}

Test B is designed to handle selectable items. The challenge lies in notifying Test A when an item is selected...

I believe there are two possible solutions for this scenario.

  • The first option involves using the App component as a middleman to store and pass along the selected item information between Test B and Test A. However, this approach creates a rather tight coupling between the components that may not be ideal.
  • The second option proposes creating an "Event Subscriber" service that manages a collection of Observables which can be subscribed to. My initial implementation draft is outlined below:

// This is the model needed for my custom class

export class KeyValuePair<T>
{
    public key: string;
    public value: T;

    construct(key: string, value: T) {
        this.key = key;
        this.value = value;
    }
}

// Preliminary implementation of the concept (work in progress)

import { Observable, of } from "rxjs";
import { KeyValuePair } from "../models/keyvaluepair";
import { Injectable } from "@angular/core";

@Injectable({
    providedIn: 'root',
})
export class EventService<T>
{
    protected subscriptions: KeyValuePair<Observable<T>>[];

    public Broadcast(key: string, value: any)
    {
        var observable = new Observable<T>();
        observable.subscribe((a) =>
        {
            return of(value);
        });

        this.subscriptions.push(
            new KeyValuePair<Observable<T>>(
                key, 
                observable
            )
        );
    }

    public Subscribe(key: string): Observable<T>
    {
        var observable = this.subscriptions.find((sub) => {
            return sub.key == key;
        });

        return observable.value;
    }
}

// How to trigger an event

this.testEventService.Broadcast("itemSelected", item);

// Sample usage

this.testEventService.Subscribe("itemSelected").subscribe((item) => {
    this.changeItem(item);
});

Despite this solution, I can't help but wonder if there's a simpler way to achieve the desired functionality... In previous frameworks like AngularJS and jQuery, features such as $broadcast and $on simplified event handling. Is there a more straightforward approach in Angular 6 and TypeScript?

Edit:

I've created a service that others can use. Please provide feedback on its effectiveness: https://jsfiddle.net/jimmyt1988/oy7ud8L3/

Answer №1

Utilizing the Subject is recommended.

export class EventService<T> {
    protected _eventSubject = new Subject();
    public events = this._eventSubject.asObservable();

    triggerEvent(event) {
       this._eventSubject.next(event);
    }
}

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

Kendo checkbox toggle issue with switching between true and false states is not functioning correctly

How can I make a button appear when one or more checkboxes are clicked? Currently, the toggle function only activates when I select one checkbox, and then deactivates upon selecting another. Any guidance on improving this functionality would be greatly app ...

The number in Typescript should fall between 0 and 1, inclusive

Is there a method in Typescript that guarantees the value of a number will be less than or greater than a certain threshold? Currently, it permits the specification of a range of values, but I'm unsure about comparison. This is similar to what I have ...

Troubleshooting: HTTP client post request working with body.set but not with formData.append for sending data to API

I am in the process of updating the UX for an older application with APIs developed in ASP.NET When I make a POST request as shown below, everything works perfectly. The data is received: var APIURL = sessionStorage.getItem('endpoint') + "/ ...

Issue with passing incorrect props to child component occurs specifically on pages 2 and beyond within react-table

Implementing a button in each row of a table using react-table to trigger a react-modal is functioning correctly on the initial page. However, when navigating to subsequent pages, an issue arises where the incorrect id prop is being passed into the custom ...

Steps to Validate a Form: To allow the submit button to be enabled only when all input fields are filled out; if any field is left empty,

https://i.sstatic.net/AHlJX.png Is it possible to enable the send offer button only after both input boxes are filled? I'm sharing my code base with you for reference. Please review the code and make necessary modifications on stackblitz 1. exampl ...

Deploy your Angular2 application with a specified base URL

I am embarking on the journey of Angular2 web app development. After successfully creating an Angular2 application using angular-cli, I am now faced with the challenge of deploying it to my Tomcat server. Following the ng build command, a dist folder was ...

A step-by-step guide on updating environment configurations in VSTS Release Management

I am exploring the use of VSTS Release Management to streamline the deployment process for my Web Application across various deployment locations (dev, test, prod). Currently, I rely on different builds to achieve this, but I aim to consolidate everything ...

Monaco utilized for Angular web-based code editing platform

We recently created an online code editor in our project using the Monaco editor. Our next goal is to integrate an Angular editor into this platform. To achieve this, we require NPM support to install dependencies directly from the editor. If anyone has ...

How can I ensure that PrimeNG is functioning properly?

I'm encountering some difficulties setting up PrimeNG correctly to utilize its rich text editor. Despite installing all the necessary components, it's still not functioning as expected. https://i.stack.imgur.com/4kdGf.png This is my package.jso ...

What sets apart Record<key, type> from [key: string]: type?

Can someone explain the distinction between Record<key, type> and [key: string]: type? Are they interchangeable? Which one offers more flexibility and type safety? I have come across a situation where both were used interchangeably. Is there a prefe ...

What could be causing the incomplete transmission of data to the mongodb database?

Can anyone help me with my Angular CRUD operation issue? I am facing a problem where only the _id is being stored in the MongoDB database when trying to add a new person. The rest of the data is not getting sent completely. Here's my code: var expres ...

Transform Typescript into compiled css files without using any additional tools

Currently, I am working on a monorepo project where the main project relies on another project called components. When running the entire monorepo, the main project utilizes webpack.dev while the components project simply uses the TypeScript compiler. It l ...

Both primary and accent colors in the Angular Material theme are identical

I have developed a unique theme where the primary color appears as green and the accent color also shows as green, but it should actually be yellow! When I use this code $my-theme-accent: mat-palette($mat-pink, A200, A100, A400); However, when I use $m ...

Tips for updating view according to the check box selected?

I'm currently working on implementing filters for various products using a JSON object. Expected Result: When the filter checkbox is clicked, the product list should display only the filtered products. Current Result: Filtered products are being add ...

"Exploring the possibilities of Angular 6 through custom pipe

Is there a way to integrate a custom pipe from an Angular 6 library into my main app? I have been attempting to do so in the following manner: @NgModule({ declarations: [ SomePipe ], exports: [ SomePipe ]}) Within public_api.ts: export * fr ...

Encountering an error with d3.line() in angular2 when combining d3v4 with Typescript. The x function is not working as expected

So here's my setup... import { D3Service, D3, Selection } from 'd3-ng2-service'; interface ChartData { q: number, p: number } export class GraphComponent implements OnInit{ private d3; private x1; private y; construc ...

Encountering a duplication issue when redirecting components in Angular2/TypeScript using navigateByUrl

Seeking guidance on implementing the login function where the current component redirects to another one upon clicking the login button. Below are my .ts and .html files: login.component.ts login.component.html The issue arises when using npm start for ...

Dealing with circular references in class attributes within Angular

I'm facing a challenge in Angular while trying to set up mock data. I have the following two classes: export class Company { public id: number; public name: string; public applications: Application[]; constructor(id: number, name: string, ap ...

The age-old debate: Ngxs or Behavior Subject, which one should you go

I'm embarking on creating an admin panel for a Payment gateway product using Angular's latest version, working with a multitude of microservices. With experience in NGXS state management, as well as subjects and behavior subjects, I'm undeci ...

Looking to switch up the menu in Angular 6

Looking to toggle the side navigation bar, I have: Created a boolean variable toggle_menu set to true Added a function togg() on button click in the menu bar that sets the boolean value to false and toggles the div However, here's the iss ...