Angular 9 Singleton Service Issue: Not Functioning as Expected

I have implemented a singleton service to manage shared data in my Angular application. The code for the service can be seen below:

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

@Injectable({
  providedIn: 'root'
})
export class DataSharingService {
  private sharedData: any;
  
  constructor() { }
  
  public setSharedData(data: any): void {
    this.sharedData = data;
  }
  
  public getSharedData(): any {
    return this.sharedData;
  }
}

In the following component, I am utilizing the above service to share and retrieve data. Here is the implementation:

import { Component, OnInit } from '@angular/core';
import { DataSharingService } from '../data-sharing.service';

@Component({
  selector: 'app-data-component',
  templateUrl: './data.component.html',
  styleUrls: ['./data.component.css']
})
export class DataComponent implements OnInit {
  
  constructor(private dataSharingService: DataSharingService) { }

  ngOnInit() {
    // Initialization logic here
  }

  setDataAsShared(data: any) {
    this.dataSharingService.setSharedData(data);
  }

  getDataFromShared(): any {
    return this.dataSharingService.getSharedData();
  }
}

However, when trying to access the shared data in a different component (shown below), I encounter an issue where the data is returned as undefined:

import { Component, OnInit } from '@angular/core';
import { DataSharingService } from '../data-sharing.service';

@Component({
  selector: 'app-receiving-component',
  templateUrl: './receiving-component.html',
  styleUrls: ['./receiving-component.css'],
})
export class ReceivingComponent implements OnInit {

  sharedData: any;

  constructor(private dataSharingService: DataSharingService) { }

  ngOnInit() {
    this.sharedData = this.dataSharingService.getSharedData();
    console.log(this.sharedData);
  }
}

This issue has been quite perplexing as the shared data appears to be correctly updated in the service, but retrieving it in another module always results in undefined. Any insights or solutions would be greatly appreciated.

Answer №1

By adding a service to the providers array, each component and its children will receive their own instance of that service instead of sharing a singleton. Removing it from providers should resolve the issue.

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

ReactTS: Tips for organizing child components within a "container component"

Currently, I am in the process of developing reusable front-end components in React using Typescript. However, I am encountering a challenge related to a feature commonly found in traditional packages. My goal is to have the ability to nest children of a ...

Using HTML5 to display the {{data}} extracted from a JSON file right in the center of the text

Can someone help me with a question about working with html and angular5? <span [innerHTML]="'client.acceptance.explanation'| translate"></span> <span><b>{{data}}</b></span> I have text stored in a json file ...

Tips on extracting information from an AJAX call using JQuery

My current project involves utilizing a webapi in asp.net that outputs JSON data. I am looking to integrate this webapi with JQuery within a php-created website. The following is the JQuery code I am using to retrieve information from the webapi: $.ajax( ...

What is the best way to determine the left and top coordinates when resizing a draggable image within a container?

I am struggling to correctly scale the image and set the left (x) and top (y) positions. Here is the code from my template: <div id="container" :style="`height: ${height}px;width: ${size}px;overflow: hidden;position: relative;`"> ...

The Redux state is not being refreshed

I've been attempting to update the redux store by fetching a list of group names using axios within the action. Despite receiving a response from the API call, the redux store fails to reflect the updated data. FileName: actions/index.js CODE: expo ...

Converting a JS result set into JSON format

Having an issue with converting code from XML output to a JSON object instead. Here is the current code: public String evaluate() throws Exception { // Code block here } I need assistance in using GSON JSON utility methods to convert the result s ...

Monaco Editor: Module 'monaco-editor' is missing despite being successfully installed

During the development of my desktop application with electron, I encountered an issue with installing Monaco Editor. After using npm install monaco-editor, running the application resulted in a message saying Cannot find module 'monaco-editor'. ...

Troubleshooting the accessibility issue between Docker node container and Angular/Node.js

After deciding to follow the angular tutorial provided on the angular website, I made the choice to download the "node" image from dockerhub. To ensure proper functionality, I carefully mapped container ports 4200 and 8080 to my physical Windows machine po ...

Modifying array elements in JavaScript without explicit instructions

I am relatively new to Javascript and seem to be encountering a rather puzzling issue that I'm unable to resolve. Currently, I have two classes: Country and PPM_Data. The Country class contains parameters such as name, area, ppm, etc., along with a f ...

npm fails during the build process due to webpack issues

I find myself lost in trying to pinpoint the right question to ask, but I am encountering a failure while running npm run build. > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="395a5655564b14564b5e585750435c4b790817091709" ...

There is an issue with the Svelte TypeScript error related to the $: syntax, specifically stating that a declaration cannot be used in a

I encountered an issue where I am receiving the error message "Cannot use a declaration in a single-statement context" while using $: syntax in a script with lang="ts" within my +page.svelte file. Additionally, when I check the version control system (VCS) ...

This as well as its parent node

I am looking to implement a function where an element is manipulated if a child of it is clicked (by adding a CSS class to it). My current approach is as follows: function mahlzeitRaus() { console.log("Out"); //this.className += " not"; this. ...

An error occurs when using e.slice function

I am facing an issue with my kendoDropDownList that uses kendo UI and jQuery. I cannot figure out why this error is occurring. $("#drpState").kendoDropDownList({ optionLabel: "States...", delay: 10, ...

How to run 'npm' scripts externally in package.json on Windows?

In the world of development, running arbitrary commands using npm run is a common practice. This involves adding a scripts hash to your package.json: "scripts": { "build-js": "browserify browser/main.js | uglifyjs -mc > static/bundle.js" } To exec ...

Interactive material design drop-down menu

Currently, I am working on a dynamic drop-down menu that utilizes material-ui js. However, I have encountered an issue where clicking on one menu opens all the menus simultaneously, and vice versa when trying to close them. If you would like to view the c ...

Using AngularJS ng-repeat with jQuery find yields a single element result

I'm in the process of developing my very first AngularJS application, and I've run into an issue with the jQuery find function. Essentially, what I'm attempting to do is utilize a custom HTML component that contains a list of buttons generat ...

AngularJS: Issue with watching arrays and deep $watch functionality

I'm having trouble using the $watch function in AngularJS with an array of boolean values. I want to display a message when there's a change in the array, but it's not working as expected. Check out this code example where the array values ...

Navigating with React Router using URL parameters

After implementing react router with a route path taskSupport/:advertiserId that includes parameters, I encountered an issue when trying to access the link http://localhost:8080/taskSupport/advertiserId. My browser kept returning 404 (Not found) errors for ...

`Developing reusable TypeScript code for both Node.js and Vue.js`

I'm struggling to figure out the solution for my current setup. Here are the details: Node.js 16.1.x Vue.js 3.x TypeScript 4.2.4 This is how my directory structure looks: Root (Node.js server) shared MySharedFile.ts ui (Vue.js code) MySharedFi ...

Trigger Function on Input Change in Angular 2

Key aspects of component nesting: export class Child { @Input() public value: string; public childFunction(){...} } Main component responsibilities: export class Parent { public value2: string; function1(){ value2 = "a" } function2( ...