The shared service is experiencing difficulties in transferring data to the following component

I have developed two components along with a shared service. My goal is to transfer data from one component to another, but I am encountering an issue where the object appears empty. Below is the code for the first component:

import { Component, OnInit } from '@angular/core';
import {SharedService} from './../shared.service';
import { Router, NavigationStart } from '@angular/router';

@Component({
  selector: 'app-cone',
  templateUrl: './cone.component.html',
  styleUrls: ['./cone.component.css'],
  providers: [SharedService]
})
export class ConeComponent implements OnInit {
  req = <any>{};
  
  constructor(public service: SharedService, private router: Router) {}

  send(){
    this.req.fname= "ketan";
    this.req.lname= "pradhan";
    this.service.saveData(this.req); 
    console.log('str');
    this.router.navigate(['/apps/ctwo']);
  }

  ngOnInit() {

  }

}

Below is the second component where the data from the first component needs to be passed. However, I am observing that the object in `this.myName` is empty.

import { Component, OnInit } from '@angular/core';
import { SharedService } from './../shared.service';
import { Router, NavigationStart } from '@angular/router';

@Component({
  selector: 'app-ctwo',
  templateUrl: './ctwo.component.html',
  styleUrls: ['./ctwo.component.css'],
  providers: [SharedService]
})
export class CtwoComponent implements OnInit {
  myName = <any>{};

  constructor(public service: SharedService, private router: Router) {
    this.myName = this.service.getData();
    console.log(this.myName);
  }

  ngOnInit() {

  }

}

Lastly, here is the shared service that facilitates communication between the two components:

import { Component, Injectable, Input, Output, EventEmitter } from '@angular/core'

// Name Service export interface myData { name: string, lname: string }

@Injectable()
export class SharedService {
  sharingData: myData = <any>{};
  
  saveData(str){
    console.log('save data function called' + str.fname);
    console.log(this.sharingData);
    this.sharingData = str; 
    // this.sharingData.lname=str.lname; 
    console.log(this.sharingData)
  }
  
  getData(){
    console.log('get data function called');
    return this.sharingData;
  }
} 

Answer №1

When you set the providers arrays at component level, it results in having two separate instances of the service in this particular case.

To ensure that all components within a module share the same instance of the service, it is recommended to declare the service in the NgModule providers array.

To achieve this, remove the providers arrays from your components and add the service to the providers array in the NgModule.

@Component({
  selector: 'app-ctwo',
  templateUrl: './ctwo.component.html',
  styleUrls: ['./ctwo.component.css'],
  // providers: [SharedService] // remove these!
})

Instead, do the following:

@NgModule({
  imports: [ ... ],
  declarations: [ .. ],
  bootstrap: [ ... ],
  providers: [ SharedService ] // here!
})

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

Does it make sense to prioritize robust $routeProviders and keep controllers slim?

Traditionally in MVC architecture, models are designed to be robust and controllers are kept minimal for easier testing. However, Angular lacks a clear model structure, making it challenging to organize code for reuse. Although Angular does offer services ...

Show search results in real-time as you type

I am currently developing a SharePoint 2007 web part using Visual Studio. The main goal of this web part is to search a SharePoint list and present the results to the user. My objective is to have the results displayed automatically once the user finishes ...

Encountering a duplication issue when redirecting components in Angular2/TypeScript using navigateByUrl

Seeking guidance on implementing the login function where the current component redirects to another one upon clicking the login button. Below are my .ts and .html files: login.component.ts login.component.html The issue arises when using npm start for ...

An element failing to submit using AJAX requests

I have a login form with an <a> element that I want to use for making a post request. However, when I'm examining the backend Django code during debugging, it seems to interpret the request method as GET instead of POST. HTML <form id= ...

Is data shared globally for each HTTP/Session request?

QUERY: Is there a method to establish a variable storage specific to each session or HTTP request? The variable should be accessible globally within that session/request/connection, without the need to pass it between functions. For instance (as an examp ...

There is no overload match for the HttpClient.get call at this time

I'm trying to set up a file download feature using a blob, but I need to extract the filename from the server's "content-disposition" header. Here's the code I have: const header = {Authorization: 'Bearer ' + token}; const config ...

When attempting to import Quill-blot-formatter with react-quill via next/dynamic, the registration process fails and continues to display a loading message

After creating a function component and configuring quill-blot-formatter with react-quill, I added the blotFormatter to the modules list. Then, I imported this module using next/dynamic on the desired page. The custom function looks like this: import Reac ...

Can you explain the purpose of this function on Google PlusOne?

Within the code snippet below: (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByT ...

Utilize the cart data object to calculate the grand total

Need help accessing individual item properties in an array to calculate the total order amount separately from the table. <Table className={classes.table} aria-label="simple table"> <TableHead& ...

.slideDown Not Functioning Properly on my System

After successfully linking my index.html file to jQuery, I am facing an issue with the .slideDown code. I'm not sure if there is a problem with the code itself or if I didn't attach jQuery correctly. Can anyone help me troubleshoot this? Below i ...

Unable to display grid items in React material-ui grid list

export interface FlatsGridProps { flats: IClusterFlats[]; } export const FlatsGrid: React.StatelessComponent<FlatsGridProps> = (props: FlatsGridProps) => { if (props.flats.length === 0) { return (<div> empty </di ...

Tips for setting environmental variables to match ID values in html documents

In my API reference call, I have stored the key in a separate file and protected it using .gitignore since I am using GitHub. However, I am facing an issue on how to transfer that key from my JavaScript file into the HTML data-key attribute using a variab ...

Steps to retrieve numerical input value upon button click:

I'm wondering how to retrieve the value of a dynamic button in my code snippet below: <p *ngFor = "let product of ProductsDetails; let i = index"> <input type="number" value={{cartProducts[i].amount}} class="quantI ...

Arrangement of Angular DI assembly order

Within my Angular application, I have a service called user-serial-service. This service makes an API call to retrieve a user serial as a string and then stores this value within a BehaviourSubject. The issue I am facing is that I want to access this user ...

The default data value in the Vue component is taking precedence over the value I specified in beforeRouteUpdate

When navigating in my Vue application, I utilize vue-router's beforeRouteEnter and beforeRouteUpdate to retrieve data from a REST API. <template> <div> <h2>{{ league.name }} </h2> <user-list :users="league.leaderb ...

What is the best way to update the src of an input using an onclick event?

When I click the input, my background changes color as expected. However, the src of the input only changes on the second click. How can I make it change the source on the first click? Also, how can I change the src back to the original with a second cli ...

Encountering the "ERPROTO" error message while attempting to send an Axios request from my REST API

I have set up my API at "localhost:3000/api/shopitems" and it successfully returns the JSON data below when accessed through a browser: [ { "item_available_sizes": { "s": 1 }, "imgs": { "album": [], ...

Having trouble establishing a connection to SQL Server with tedious in Node.js

Trying to connect to the SQL Server "SQL.SCHOOL.EDU\STUDENTSQLSERVER,4500" from my school has been a real challenge for me using tedious. I am currently working on setting up a connection between my express back end and react front end. For now, I am ...

The inclusion of a content editable feature within a carousel is leading to unexpected event propagation

I am dynamically creating an editable div using the code snippet below. <div class='reflection-field' contenteditable="true" data-number="${index}"></div> Expected Outcome: When I click on the generated div, I anticipate that the c ...

Guide on toggling visibility of a column in Material-ui based on a conditional statement

Can someone help me with code that allows me to hide or show the TableCell based on an if statement? I am currently working with MATERIAL-UI framework which can be found here: https://material-ui.com/ <TableBody> {Object.entries(servicesCode).map ...