Initiate function by using event broadcaster

Is it feasible to activate a function in a different component from the current one using EventEmitter, acting similar to a callback mechanism? For instance, following the completion of an API request, a successful function is triggered as shown below:

@Output() afterAPIRequest = new EventEmitter();

handleSuccess() {
   this.afterAPIRequest.emit();
}

Now, is there a way to capture that event in another component and execute another function, like this?

// upon emission, run this

refreshListIfEmitted() {
   this.refreshMyList();
}

Answer №1

utilize a service

import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';

@Injectable()
export class MessageService {
  private _message: Subject<any>;

  constructor() {
    this._message = new Subject();
  }

  get updates(): Observable<any> {
    return this._message.asObservable();
  }

  set communication(message: any) {
    this._message.next(message);
  }
}

module one

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-one',
  templateUrl: './one.component.html',
  styleUrls: ['./one.component.scss'],
})
export class OneComponent {
  constructor(private _http: HttpClient, private _message: MessageService) { }

  handleAPICall(): void {
    this._http.get('end-point').subscribe(value => this._message.communication = value);
  }
}

module two

import { Component } from '@angular/core';

@Component({
  selector: 'app-two',
  templateUrl: './two.component.html',
  styleUrls: ['./two.component.scss'],
})
export class TwoComponent {
  constructor(private _message: MessageService) {
    this._message.updates.subscribe(value => console.log(value));
  }
}

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 the best way to store data from multiple selected rows in different datagrids into a single state?

Programming Languages : JavaScript with React, Redux Toolkit, and Material-UI Issue : My goal is to synchronize the selection of checkboxes across multiple datagrids into one central state Attempts Made : I first attempted to manage checkbox selection fo ...

What is the process for implementing custom color props with Material-UI v5 in a React TypeScript project?

Looking to enhance the MUI Button component by adding custom color props values? I tried following a guide at , but encountered errors when trying to implement it in a custom component. The custom properties created in createPalette.d.ts did not work as ex ...

Generate TypeScript type definitions for environment variables in my configuration file using code

Imagine I have a configuration file named .env.local: SOME_VAR="this is very secret" SOME_OTHER_VAR="this is not so secret, but needs to be different during tests" Is there a way to create a TypeScript type based on the keys in this fi ...

Text box size in user input not adapting on mobile devices

Website: Visit the Cutter Travel Calculator here I've encountered an issue with my user input text boxes on mobile. Despite setting their width using the formidable forms plugin, the size adjustment doesn't seem to apply when viewed on mobile de ...

Using jQuery to dynamically swap out <tr> tags and all the elements inside of them

In order to enhance user experience, I am looking to automatically fill in certain form elements within a table when a link is clicked. The intention is for the fields to populate with predefined values and then convert into HTML paragraph elements, preven ...

MacGyver's innovative Angular mac-autocomplete directive fails to properly auto-complete

I have incorporated the .css and .js files for MacGyver in my HTML document. Additionally, I have added 'Mac' as a dependency in my Angular application. The following code snippet is included in my HTML: <mac-autocomplete ng-model="selected" ...

Check that the elements within the array are present in the observable array

I need to confirm whether the items in the array below: const payment1: Payment = new Payment('1000'); // 1000 = id const payment2: Payment = new Payment('1001'); const paymentArray: Payment[]; paymentArray.push(payment1, payment2); ...

Angular 4 app.module.ts encountering a bug

Currently, I am tackling a challenge with the tree view control within Angular 4. My stumbling block lies with providers in app.module.ts file, as shown below: import { NgModule, ErrorHandler, Injector } from '@angular/core'; import { BrowserMod ...

Error in Angular Universal: KeyboardEvent is not defined

I have inserted the word "domino" into the server.ts file and updated the webpack.server.config.js as follows: module: { rules: [ { test: /\.(ts|js)$/, loader: 'regexp-replace-loader', options: { match: { pattern: '&bs ...

Can a variable in Typescript be defined to accept any value as long as it follows a specific format?

For instance, I am searching for a way to represent any value that consists of two strings separated by an underscore "_". I attempted something along the lines of: let key:string = string1 + "_" + string2; Upon entering this code, I quickly realized ...

Setting up the viewport addon in Angular can be done by following these steps

After checking this documentation, I attempted to add a custom viewport in the config.js file: import { setParameters } from '@storybook/angular'; // switching from react to angular import { INITIAL_VIEWPORTS } from '@storybook/addon-viewpo ...

Modify the color of the 'li' element that shares the same attribute value as the current page

I am in the process of creating a website for an architecture company. Currently, I am working on a specific page which you can find here: . Each project falls into a category such as residential, commercial, or education. On each project page, I include t ...

Steps to initiate or conclude a conversation from a designated location?

I'm working on an Angular project where I have a popup dialog open. However, I want the dialog to appear from the button and close within the button itself, similar to this example: https://material.angularjs.org/latest/demo/dialog Opening and closin ...

Error encountered when utilizing a mixin in TypeScript due to a parameter issue

Recently, I delved into learning Typescript and decided to experiment with the mixin concept. The code snippet below may seem trivial, but it's all part of the learning process. Surprisingly, everything runs smoothly except for line 42, myInput.sendKe ...

leveraging jQuery across an Angular 2 application as a global tool

I'm currently exploring ways to incorporate jQuery globally throughout my angular 2 application. The only comprehensive resource I've come across so far is this Stack Overflow answer. However, despite my efforts, I haven't been able to make ...

Is there a way to display my modal separately from my sidenav while utilizing :host in Angular?

I implemented a :host with hostlistener() in my navmenu-component.ts to enable a sidemenu that slides out from my sidenavbar when a button is pressed. My goal is to display a modal for editing purposes. I have included the modal in the navmenu-component.h ...

What is the best way to define a signal within a class interface in Angular 17?

I’m working on setting up signals for my properties in class, which has been going smoothly so far. public varName = signal(''); However, I would also like to utilize the related interface. Unfortunately, I have not come across any documentati ...

Leveraging the @Input decorator to send external data into the Angular component

In my Ionic app, I am utilizing an Angular component. Within this component, there is a variable called headerText that is supposed to be initialized from the page where the component is being used. The issue arises when the headerText variable is always ...

Is the 'Access-Control-Allow-Origin' header preventing the retrieval of cross-domain JSON data?

My goal is to retrieve a JSON object from the following URL. I attempted to use the XMLHttpRequest() function in JavaScript, but encountered an error in the console: [CORS] The origin 'http://localhost' did not find 'http://localhost' i ...

Having difficulty with utilizing the validate() function in jQuery

My HTML code looks like this: <form class="form-filter" id="form-filter-excel" role="form"> <div class="row"> <div class="col-md-4 col-sm-5"> <label>Date range</label> ...