Utilizing Angular 6 for Efficient Message Passing between Components via Services

Currently, I am experimenting with a way to transmit a message from app.component.ts in order for it to be shown in messageComponent.ts

In app.component.html, I have included

<app-messagecomponent></app-messagecomponent>

However, at the moment, nothing is being displayed.

Additionally, there is a method in a service:

Within message.service.ts:

message(message) {
    return message;
}

My goal is to pass a message from other components using the message service so that it appears in the app-messagecomponent.html

For instance, within app.component.ts:

sendMessageToService() {
    this.myservice.message('my Message to be displayed in the messageComponent');
}

I am looking for guidance on how to achieve this. Can you help?

Answer №1

If you need to communicate a message from one component to another using a service, one approach is to establish a global message bus or event bus (known as the publish/subscribe pattern).

To achieve this, you will require the use of the Subject (for emitting values with the .next() method) and Observable (for subscribing to messages with the .subscribe() method) from RxJS, which has become an integral part of Angular 6. In this example, I am utilizing RxJS 6 in combination with the rxjs-compat package.

In this scenario, we will send a message through the MessageService class, annotated as @Injectable for dependency injection in components. The message will be triggered by clicking a button in app.component.html, and then retrieved in message.component.ts to display it in the HTML template message.component.html. To include the selector for MessageComponent, use in app.component.html.

Below is the complete code:

message.service.ts

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

@Injectable()
export class MessageService {
    private subject = new Subject<any>();

    sendMessage(message: string) {
        this.subject.next({ text: message });
    }

    clearMessage() {
        this.subject.next();
    }

    getMessage(): Observable<any> {
        return this.subject.asObservable();
    }
}

app.component.ts

import { Component } from '@angular/core';
import { MessageService } from './message.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular 6';

  constructor(private service:MessageService){}

  sendMessage(): void {
        // send message to subscribers via observable subject
  this.service.sendMessage('Message from app Component to message Component!');   
  }

  clearMessage():void{
    this.service.clearMessage();
  }
}

app.component.html

<button (click)="sendMessage()">Click here to test message</button> <br><br>
<app-messagecomponent></app-messagecomponent>

message.component.ts

import { Component, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { MessageService } from './message.service';

@Component({
    selector: 'app-messagecomponent',
    templateUrl: 'message.component.html'
})

export class MessageComponent implements OnDestroy {
    message: any = {};
    subscription: Subscription;

    constructor(private messageService: MessageService) {
        // subscribe to app component messages
        this.subscription = this.messageService.getMessage().subscribe(message => { this.message = message; });
    }

    ngOnDestroy() {
        // unsubscribe to ensure no memory leaks
        this.subscription.unsubscribe();
    }
}

message.component.html

<p>The incoming message :  </p>  <br>
{{message?.text }}

The Elvis operator is utilized here in case the message is undefined.

Here is a working demo: https://stackblitz.com/edit/rxjs-snaghl

Feel free to reach out if you are interested in implementing a similar solution.

Answer №2

Utilize input to achieve the same functionality

< app-messagecomponent [YourInputVariableName]= "YourMessage" >< /app-messagecomponent>

Add the following code in app.component:

YourMessage:any='my Message to be displayed in the messageComponent';

In app-message.component add:

@Input YourInputVariableName:any;

You can display the message in app-messagecomponent using this.YourInputVariableName

Answer №3

Utilize the ng-interconnect library to enable seamless data exchange between different angular entities.

With ng-interconnect, you can easily broadcast or receive data from multiple sources.

For instance, in a broadcasting scenario:

Create a broadcaster instance for 'home/stateChanged':
let messageStream: IMessageStream = createBroadcaster('home/stateChanged');
 
/* Receive data from this broadcaster in another component within the hierarchy */
let userReceiver = receiveFrom('home/stateChanged', 'contacts/user', (data, error, complete) => {
  console.log(data);
  console.log(error);
  console.log(complete);
})
 
/* Broadcast messages from the first component */
messageStream.emit('logged-in');

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 message: Dockerfile for angular-cli application reports "ng: command not found"

I've been attempting to launch my Angular application (created using the ng-cli) within a docker file. Here's what my docker file looks like: FROM node:6.10.0 RUN mkdir -p /usr/src/app WORKDIR /usr/src/app COPY package.json /usr/src/app/ RUN ...

Validating a field conditionally upon submission

Adding a required validation conditionally to the "imageString" field upon submission, but the expected required validation is not being set. Initializing the form. constructor(){ this.poeForm = this.fb.group({ imageString: [""], imageFileNam ...

Tips for generating search engine optimized URLs with category/subcategories/article slug in an Angular application

Currently, I am utilizing Angular 8 Version to develop a news application. My objective is to showcase the link in the following format: www.domain.com/category/category/title and www.domain.com/category. Can you guide me on how to accomplish this task? T ...

Receive the traits of a React component

Hey there, I'm currently working with typescript and react. I am trying to create a base class that multiple components can inherit from. import * as React from "react"; interface IBaseProps { title: string; } class Base<P extends IBaseProps ...

Sharing a variable between an Angular component and a service

I am attempting to pass a variable from a method to a service. from calibration-detail.component.ts private heroID: number; getTheHeroID() { this.heroService.getHero(this.hero.id).subscribe(data =>(this.heroID = data.id)); } to step.service.ts I ...

Encountering an issue with Auth0 and Angular2: "The supplied parameters do not match any signature of call target."

I'm currently in the process of integrating Auth0 with my Angular2 application using angular2-cli. I've added a new service called auth, but when I try running npm start, I encounter an error stating: src/app/auth.service.ts (21,5): Supplied para ...

ngx-loading is a fantastic addition to Angular 7, ensuring that the spinner is continually visible

While using ngx-loading to display a spinner during server response retrieval, I encountered an issue. The spinner works properly by appearing when the request is sent and disappearing once the server response is received. However, if I click on the area w ...

Converting Typescript Object Types to Array Types with Tuple Structures

Presently, I have the following: interface Obj { foo: string, bar: number, baz: boolean } The desired outcome is to convert this interface into the tuple format below: [string, number, boolean] Is there a way to achieve this conversion? Up ...

Challenges encountered when testing middleware in a TypeScript Node.js Express project

I have been exploring the repository at https://github.com/goldbergyoni/nodebestpractices to enhance my understanding of nodejs best practices. Below is a middleware I developed: import { NextFunction, Request, Response } from "express"; import ...

Error occurs because the declaration for `exports` is missing in the compiled TypeScript code

I am currently venturing into the world of typescript and I've encountered a problem while attempting to run my application. An error is popping up, stating ReferenceError: exports is not defined The code I have written is rather straightforward: / ...

Updating the background color of the side menu in Ionic 4

Wanting to customize the background color of the side sliding menu in my ionic 4 project Here is the code I am using: <ion-app> <ion-split-pane> <ion-menu> <ion-header> <ion-toolbar color="medium"> ...

The input in the schema fails validation against the Angular 7 schema with the following data: {"name":"testng7"}

After updating the Angular CLI to the latest version on my Mac OS, I encountered an issue when trying to create a new project using the command ng new testng7. The error message displayed was: Schematic input does not validate against the Schema: {"na ...

How to conceal the side navigation bar on specific pages or components within an Angular application

Currently immersed in developing a web application with Jhipster and Angular. I've managed to set up a side navbar along with a top navbar on every page. However, I'm struggling to hide the side navbar on specific pages and could use some guidanc ...

Is there a way to alter the date format for input elements within formGroups using Angular 7?

When the input is of type 'Date', the date format is dd/MM/yyyy. I need to convert the date format from MM/dd/yyyy to dd/MM/yyyy (Turkish Format and Turkish Calendar). Below is the code snippet. <form [formGroup]="opportunityForm" (ngSubmit ...

Tips on navigating an array to conceal specific items

In my HTML form, there is a functionality where users can click on a plus sign to reveal a list of items, and clicking on a minus sign will hide those items. The code structure is as follows: <div repeat.for="categoryGrouping of categoryDepartm ...

issue with integrating promise in angular 4

I'm currently learning about promises and how to implement them in Angular. I have written the following code in StackBlitz. My goal is to display the array whenever it contains a value by using promises in Angular. This is my HTML code: <h2>A ...

Does anyone know of a npm package specifically designed for handling audio in Angular 4?

Currently, I am working on setting up an angular 4 application that is connected to the PubNub service. The ultimate goal is for one device to send a signal that triggers a sound on another device (preferably a mobile). Do you happen to know if there is ...

Utilize ngModel to access input files in the array

Within my form, there is a file upload input: <input type="file" [(ngModel)]="item.image" name="image" #image> Can I retrieve #image.files[0] using the ngModel item.image directly (without creating a reference)? If not, what exactly does ngModel s ...

The Firebase.update operation in AngularFire2 encountered an error due to a failure in snapshot

I'm currently working on an Angular2 project and I need to update user profiles in Firebase using AngularFire2. However, I'm encountering an error when trying to update a user profile with the key "nmH5ZmawpQgogoCRVFVfNaBN6xg1". The specific erro ...

Discover the power of Angular RxJs in efficiently iterating through an array and consolidating multiple http get requests into a single,

I'm currently seeking assistance with looping through an array of string numbers and assigning HTTP GET requests to each string number. I want to aggregate the results into a single reactive observable provided by my service. While I managed to achiev ...