Sharing information between components in Angular through service communication

In my Angular 4 project, there is a functionality where upon clicking on one of the 'groups', its tile should be added to a list of 'favourites' which is represented as an array. To implement this feature, I utilized a BehaviorSubject. While I am able to display the default message on my FavouriteComponent.html, I encountered an issue when attempting to update the value upon calling the newMessage() function from GroupComponent.ts. The displayed value in FavouriteComponent.html remains unchanged and still shows the default message. I would appreciate guidance on identifying where I might have made a mistake or if there is an alternative approach to achieve the desired behavior.

Below are excerpts from the code:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

@Injectable()
export class DataService {

  private messageSource = new BehaviorSubject("default message");
  currentMessage = this.messageSource.asObservable();

  constructor() { }

  changeMessage(message: string) {
    this.messageSource.next(message)
  }

}

FavouriteComponent.ts

import { DataService } from "../data.service";

@Component({
  selector: 'app-parent',
  template: `
    {{message}}
  `
})

export class FavouriteComponent implements OnInit {

  message:string;

  constructor(private data: DataService) { }

  ngOnInit() {
    this.data.currentMessage.subscribe(message => this.message = message)
  }

}

GroupComponent.ts

import { DataService } from "../data.service";

@Component({
  selector: 'app-sibling',
  template: `
    {{message}}
    <button (click)="newMessage()">New Message</button>
  `,
  styleUrls: ['./sibling.component.css']
})
export class GroupComponent implements OnInit {

  message:string;

  constructor(private data: DataService) { }

  ngOnInit() {
    this.data.currentMessage.subscribe(message => this.message = message)
  }

  newMessage() {
    this.data.changeMessage("new title to add")
  }

}

Answer №1

Give this a try.

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

@Injectable()
export class DataService {

  private messageSource = new Subject<String>();

  constructor() { }

  public getMessage(): Observable<String> {
    return this.messageSource.asObservable();
  }

  public setMessage(message: String) {
    return this.messageSource.next(message);
  }

}

export class FavouriteComponent implements OnInit {

  message:string;

  constructor(private data: DataService) { }

  ngOnInit() {
    this.data.getMessage.subscribe(message => this.message = message)
  }

}

export class GroupComponent implements OnInit {

  message:string;

  constructor(private data: DataService) { }

  ngOnInit() {
    this.data.getMessage.subscribe(message => this.message = message)
  }

  newMessage() {
    this.data.setMessage("new title to add")
  }

}

I hope you find this information helpful.

Answer №2

Delete the variable currentMessage and start listening to messageSource instead (set it as public)

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

In Angular 2, you can include a routerLink in a child component that directs to the root

Currently, I am developing a web application using Angular 2 Beta 8 and encountering an issue with nested routes while utilizing the routerLink directive. The structure of the router is as follows: AppCmp |-> NewItemFormCmp |-> UserDashboardCmp ...

The RemoveEventListener function seems to be malfunctioning within Angular2 when implemented with TypeScript

I am currently incorporating three.js into Angular2. The code I am using is quite straightforward, as shown below. this.webGLRenderer.domElement.addEventListener('mousedown', ()=>this.onMouseDown(<MouseEvent>event), false); this.webGLR ...

The function 'appendChild' is not recognized on the type 'unknown'.ts(2339)

I'm encountering an issue while trying to integrate the Utterances component into my articles. Upon attempting to build the site, I receive the following error message: "Property 'appendChild' does not exist on type 'unknown' ...

In the context of Angular applications, how can a state be defined?

Exploring the world of NgRx for the first time and diving into its documentation, I stumbled upon this statement: "State is a single, immutable data structure." In plain terms, what exactly does "state" refer to? Can you provide some basic examples to ...

Is it true that a TypeScript derived class is not allowed to have identical variable names?

Why is it not allowed for TypeScript derived classes to have the same variable name, even if these members are private? Is there another way to achieve this, or am I making a mistake? class ClassTS { private nom: string = "ClassTS"; ...

Angular File Upload Button Tutorial

English is not my first language, so please excuse any mistakes. I recently started learning Angular and I'm attempting to build a file upload button that lets users upload files based on dropdown menu options (such as USA States). Once uploaded, the ...

Ways to redirect to a different page following a successful execution of a mutation in React-query

I am facing an issue where a memory leak warning appears when I redirect to another page after a mutation. Despite trying various methods, I have not been able to find a solution. The specific warning message is: Warning: Can't perform a React state ...

How do you verify an OpenID Connect access token produced by Azure AD v2 in an ASP.NET Core web API?

What is the best way to verify an OpenID Connect Access Token generated by Azure AD (v2) in ASP.NET Core Web API? Here's the situation: I have an Angular 8 Client Application that receives an OpenID Connect access Token post Login. The Client can us ...

What is the best way to retrieve JSON data from a raw.github URL and save it into a variable?

Suppose there is a JSON file named data.json on Github. The raw view of the file can be accessed through a URL like this: https://raw.githubusercontent.com/data.json (Please note that this URL is fictional and not real). Assume that the URL contains JSON ...

Starting a fresh Angular project yields a series of NPM warnings, notably one that mentions skipping an optional dependency with the message: "npm

Upon creating a new Angular project, I encounter warning messages from NPM: npm WARN optional SKIPPING OPTIONAL DEPENDENCY: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="68e01b0d1e0d061c7518d7">[email protecte ...

How to manually set the value of a select object in Angular 5

I am facing an issue with setting an object value manually for a select element. I have attempted to use setValue or patchValue with Object, but unfortunately, it did not yield the desired result. <mat-select placeholder="Selecione a resposta" (change) ...

Refreshing the page causes TypeScript Redux to lose its state

custom/reducer/shoppingReducer.ts import { createSlice, PayloadAction } from "@reduxjs/toolkit"; import { ShoppingReducerInitialState } from "../../types/reducer-types"; import { ProductItem, ShippingDetails } from "../../types/typ ...

Create a Typescript function that adheres to a specified type

Imagine a scenario where a specific type of function is declared within a type type Callback = (err: Error | null, result: any) type UselessFunction = (event: string, context: any, callback: Callback) => void The objective is to declare functions that ...

Enabling output hashing for Django and Angular setup

After setting up my Django and Angular 9 application based on the guidelines in this helpful post: https://medium.com/swlh/django-angular-4-a-powerful-web-application-60b6fb39ef34, I am looking to implement output hashing to prevent caching issues with bro ...

Resolving the Challenge of Disabling typescript-eslint/typedef in Angular 13 with ESlint

I started a fresh project in Angular 13 and configured typescript-eslint by running the command below: ng add @angular-eslint/schematic I made changes to my .eslintrc.json file where I disabled the rules for "typescript-eslint/typedef" and "typescript-esl ...

Angular keeps FormArray elements' validity up-to-date as new elements are added to the array

I am facing an issue where I do not want the validators to run unnecessarily. Every element of FormArray is being validated asynchronously, so I prefer the validators to be triggered only when the control's value actually changes. It seems odd that va ...

Angular/NX - Element 'Component' is unrecognized, despite being imported within the module

Encountering the following issue: 'apocaloot-building' is showing as an unknown element: If 'apocaloot-building' is supposed to be an Angular component, please ensure that it is included in this module. The component in question is ...

Implementing reduce for filtering and mapping in TypeScript: A comprehensive guide

I encountered a problem with my code that I need help fixing. Here is a simple example: interface employer { name: string; age: number; } const arr: employer[] = [{name:'Amy',age:18},{name:'Bob',age:20}]; l ...

What are the best ways to troubleshoot my Angular 2 project?

I've been searching for my TypeScript files in the console, but they're not showing up. I've tried everything to debug my Angular 2 project, but no luck. I can't move forward without debugging, can anyone lend a hand? ...

Setting the Node.js version in Eclipse on a Windows operating system can be easily accomplished by following these

After attempting to execute "ng serve" within Eclipse, an error message is displayed: The error states that you are currently using Node.js version v6.9.4, which is not compatible with Angular CLI 8.0+. To successfully use Angular CLI, you need to have No ...