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

Showing post response (XMLHttpRequest) on Chrome extension interface instead of Python console

I am currently developing a Chrome extension that sends a post request with information about the specific URL being browsed by the user to Flask (local host). A web scraping process is then carried out on this URL to determine a category based on the obta ...

Utilize Mapbox-GL.JS to animate several points along designated routes

I'm encountering issues with the following example: Animate a point along a route My goal is to add another point and routes in the same map container. Here's what I've tried so far: mapboxgl.accessToken = 'pk.eyJ1IjoicGFwYWJ1Y2t ...

Verification of Form Submission

Looking for some help with web design, specifically regarding cache issues. I have a website where form data is submitted from form.php to buy-form.php. I'm trying to set up a cache error in Google Chrome so that when buy-form.php is accessed directl ...

PHP - contact form is live for just 2 hours daily

Hello, this is my first time here and I could really use some assistance. Please bear with me as English is not my strong suit compared to most people here, but I'll do my best to explain my query. So, I have a PHP script for a contact form on my web ...

Utilizing Piwik Analytics in jQuery Mobile Framework

Having an issue with tracking users on my mobile Web App using Piwik. Due to AJAX, only views on the first page are being tracked. I attempted to use the pageinit function to load the Piwik tracking script on every page, but it still only tracks the firs ...

Flask Modal fails to function properly in the absence of table data

I'm currently troubleshooting an issue with my modal on a Flask web app that utilizes a SQLite database. When trying to add new rows to the table using some JavaScript code, everything works perfectly unless the table is empty. In that case, I am unab ...

Retrieving information from an Object within a JSON response

After calling my JSON, I receive a specific set of arrays of objects that contain valuable data. I am currently struggling to access this data and display it in a dropdown menu. When I log the response in the console, it appears as shown in this image: htt ...

What steps should I take to fix this Angular 8 error?

Encountered an issue in ../node_modules/@angular/http/src/backends/jsonp_backend.d.ts:1:28 - error TS2307: Module 'rxjs/Observable' not found. 1 import { Observable } from 'rxjs/Observable'; ~~~~~~~~~ ...

Is it possible to designate a Typescript generic type as a tuple with equal length to that of another tuple?

Imagine having a function that takes in a dataset which is an array of (identically-typed) tuples: type UnknownTuple = any[] function modifyDataStructure<T extends UnknownTuple>(list: T[]) { ... } The goal is to define a second argument with the ...

Is there a method to automatically eliminate all unnecessary properties in an Angular project?

In my extensive Angular project, I suspect that there are numerous declared properties in .component.ts that are not being used. Is there a method available to automatically eliminate all unused properties within an Angular project while also taking into ...

Automatically closing the AppDateTimePicker modal in Vuexy theme after selecting a date

I am currently developing a Vue.js application using the Vuexy theme. One issue I have encountered is with a datetimepicker within a modal. The problem arises when I try to select a date on the datetimepicker component - it closes the modal instead of stay ...

The error message "Error: 'x' is not a defined function or its output is not iterable"

While experimenting, I accidentally discovered that the following code snippet causes an error in V8 (Chrome, Node.js, etc): for (let val of Symbol()) { /*...*/ } TypeError: Symbol is not a function or its return value is not iterable I also found out ...

Live AJAX inquiries in progress

Is there a way to track the number of active AJAX requests in jQuery, Mootools, or another library similar to Prototype's Ajax.activeRequestCount? I am looking for a method that can be used across different libraries or directly through XMLHttpRequest ...

Version 5 of Material UI has a bug where the Grid component does not properly stretch

How can I make the Grid component stretch when one of the Card components contains extra text? You can view the sample code here. Changing the alignItems property to "flex-end" or "center" works, but when using alignItems: "stretch" it does not work. I ...

Design interactive Vue form with customized questions based on user response

I am looking to dynamically create a form with conditional fields. The structure of the form is stored in an object called Q. Below is an example of a Vue component that utilizes bootstrap-vue. <template> <div> <div v-for="q of ...

Tips for updating parameters that are defined in a controller within a promise

Currently, I am developing a single page application using Angular and TypeScript. I am facing an issue with updating the parameter value (_isShowFirst) of the controller inside a promise function. It seems like nothing is recognized within the promise blo ...

What is the best way to update the mat-tab when the routeParameters are modified?

I need to reinitialize the mat-tab-group in order to make the first tab active when there is a change in the routeParams. ts file: public index = 0; ngOnInit() { this.subscription = this.route.params.subscribe((routeParams: Params) => { // some ...

Validation of hidden fields in MVC architectureUsing the MVC pattern to

Depending on the selections made in the dropdown menu, certain fields will appear and disappear on the page. For example: <section> @Html.LabelFor(model => model.AuctionTypeId) <div> @Html.DropDownList("AuctionTypeI ...

Change the value of the material slide toggle according to the user's response to the JavaScript 'confirm' dialogue

I am currently working on implementing an Angular Material Slide Toggle feature. I want to display a confirmation message if the user tries to switch the toggle from true to false, ensuring they really intend to do this. If the user chooses to cancel, I&ap ...

Empty Media Viewer

I am encountering an issue with setting up a code, as it only displays a blank white page. Any suggestions on what might be causing this problem in the setup and assistance in resolving it would be greatly appreciated. <script type="text/javascript ...