Components unable to exchange data using Service

Trying to pass values from one component to another, but encountering issues with the code. The values are showing as undefined on the next page.

Below is the code for my service class named UtilityService.ts:

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

@Injectable({
  providedIn: 'root'
})

export class UtilityService {
  constructor() { }

  private message: string;

  public setMessage(message): void {
      this.message = message;
  }

  public readMessage(): string {
      return this.message;
  }
}

Here is the code for my first component:

import { Component, OnInit } from '@angular/core';
import { UtilityService } from '../UtilityService';

@Component({
  selector: 'app-products',
  templateUrl: './products.component.html',
  styleUrls: ['./products.component.css'],
  providers: [UtilityService]
})
export class ProductsComponent implements OnInit {
  private service;

  constructor(private employeeService: ProductService, utilityService: UtilityService) {
    this.service = utilityService;
    this.sendMessage();
  }

  private sendMessage(): void {
    this.service.setMessage("How are you?");
  }
}

Below is the code for my second component:

import { Component } from '@angular/core';
import { UtilityService } from '../UtilityService';

@Component({
  selector: 'app-device-list',
  templateUrl: './device-list.component.html',
  styleUrls: ['./device-list.component.css'],
  providers: [UtilityService]
})

export class DeviceListComponent implements OnInit {
  private service;
  private message: string;

  constructor(
    utilityService: UtilityService,
    private restApi: ProductService,
    private route: ActivatedRoute
  ){
    this.service = utilityService;
    this.readMessage();
  }

  private readMessage(): void {
       this.message = this.service.readMessage();
       console.log("Service message: " + this.message);
    }
}

Following an article on passing data from parent to child component in Angular, but the console.log shows undefined.

Answer №1

Your service should be provided at the module level where your components are included. Each component should have a separate instance of the UtilityService. Make sure to include your service in the declarations array of the module that includes your components.

Here's an example of how to do this:

@NgModule({
  imports: [
     ],
  declarations: [DeviceListComponent, ProductsComponent],
  providers: [UtilityService],
})
export class ProductModule {}

Answer №2

In order to prevent creating multiple instances of the UtilityService, make sure to delete the line providers: [UtilityService] from both the ProductsComponent and DeviceListComponent.

Answer №3

If you have specified providedIn: 'root' for your service, it means that the service instance will be available throughout the entire application. If this was your intention, simply remove the providers: [UtilityService] declaration from both DeviceListComponent and ProductsComponent. This should resolve the issue and everything should work correctly.

However, I suggest taking a look at the official documentation on Angular providers on the Angular Docs. This documentation explains how providedIn: 'root' works and other methods for providing Angular services.

Additionally, I would like to point you to the guide on Angular Component Interaction, where you can explore various ways to pass data between components.

Answer №4

Implement the use of BehaviourSubject within the UtilityService.

msgSource = new BehaviorSubject<any>('');
currentMsg = this.msgSource.asObservable();

Within the firstComponent, utilize BehaviourSubject's next() method to set a message.

this.service.msgSource.next("Your message");

In the secondComponent, subscribe to the currentMsg observable.

this.service.currentMsg.subscribe(msg=> {
  //TODO
}

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

What is the syntax for creating a link tag with interpolation in Angular 2 / Ionic 2?

As I work on developing an app using Ionic 2/Angular 2, I have encountered a challenge that I am struggling to overcome. Let me provide some context: I am retrieving multiple strings from a webservice, and some of these strings contain links. Here is an e ...

Using a functional wrapper component to reset the modal field in Reactstrap upon closing and reopening

In the main component that displays a list of to-do tasks, we have the ability to add or edit existing tasks. To facilitate this functionality, a separate wrapper was created. import React, { useEffect, useState } from 'react'; import { Label ...

What is the process for personalizing the appearance in cdk drag and drop mode?

I have created a small list of characters that are draggable using Cdk Drag Drop. Everything is working well so far! Now, I want to customize the style of the draggable items. I came across .cdk-drag-preview class for styling, which also includes box-shado ...

I'm struggling to find a solution to this pesky TypeScript error that keeps popping up in the button component's styling. How can

An error related to style is appearing: <Button style = No overload matches this call. Overload 1 of 3, '(props: { href : string; } & { children?: React Node; classes?: Partial<Button Classes> | undefined; color?: "primary" | ...

Issues arise when using Android BluetoothLeAdvertiser in Nativescript applications

I've been working on creating a Nativescript application that can send Bluetooth low energy advertisements. Since there are no existing Nativescript plugins for this functionality, I decided to develop a Java library (with plans to add a Swift library ...

Learn how to dynamically chain where conditions in Firebase without prior knowledge of how many conditions will be added

Currently, I am working on a project using Angular and firebase. My goal is to develop a function that can take two arguments - a string and an object, then return an Observable containing filtered data based on the key-value pairs in the object for a spe ...

Tips for using a TypeScript method decorator while maintaining the expected `this` scope

It was brought to my attention that the issue I encountered was due to the use of GraphQL resolvers in running my decorated method. This resulted in the scope of this being undefined. Nevertheless, the core of the question provides valuable insights for an ...

Exploring Geofirestore's capabilities with advanced query functionalities

Thinking about updating my firestore collection structure to incorporate geoquery in my app. Geofirestore requires a specific structure: interface GeoDocument { g: string; l: GeoPoint; d: DocumentData; } I understand that geofirestore does ...

Issue encountered while trying to insert a new row into the mat-table

I need help with inserting a new row in mat-table using a button. I wrote a function for this, but when I click the button, I encounter an error CalculatoryBookingsComponent.html:62 ERROR Error: Cannot find control with path: 'rows -> 0'. Addi ...

Introducing ngrx data - the ultimate collection service and data service that offers a custom endpoint

For my entity in ngrx/data, I required a custom PUT request and wanted to ensure its accuracy. Let's say I have a movie library where I can add tags to movies using a PUT request. This is my data service: export class MovieDataService extends Default ...

An analysis of Universal Angular.io and Prerender.io from the viewpoint of Googlebot

Currently, my website is set up with Angular 1.4.x and prerender.io, which delivers static cached pages to Googlebot. Googlebot visits each page twice - once by hitting the URL directly, and then again by appending ?_escaped_fragment_ to the URL to access ...

The optimal location to declare a constructor in Typescript

When it comes to adding properties in an Angular component, the placement of these properties in relation to the constructor function can be a topic of discussion. Is it best to declare them before or after the constructor? Which method is better - Method ...

Exploring the Power of Observables in Angular 2: Chaining and

Hi there! I'm relatively new to Angular and still getting the hang of observables. While I'm pretty comfortable with promises, I'd like to dive deeper into using observables. Let me give you a quick rundown of what I've been working on ...

What could be causing the DOM not to update after updating the data set in Angular 2?

Currently, I am facing an issue in Angular 2 where I call a function of a child component from the parent. The child function updates my data set which initially loads the HTML. However, when I call the function again while on the same HTML, it displays in ...

Leveraging jQuery within Angular 6

In the 'src' folder of my Angular app, there is a simple JavaScript file named 'my.js' slideDown(id) { $('#' + id).slideToggle(); } I am trying to figure out how to call this function by using the following code: <div ...

Angular (TypeScript) time format in the AM and PM style

Need help formatting time in 12-hour AM PM format for a subscription form. The Date and Time are crucial for scheduling purposes. How can I achieve the desired 12-hour AM PM time display? private weekday = ['Sunday', 'Monday', &apos ...

Upgrading from Angular version 12 to version 14: A Smooth Migration

After upgrading from Angular v12 to v13, I encountered issues while trying to delete the node_modules directory and reinstalling it using npm install. Unfortunately, I received the following errors: D:\test\Fxt\Web\src\main\ui ...

Issue encountered after updating to Spartacus 3.0 from 2.0: Unable to access the 'findStores' property due to a TypeError

After upgrading to Spartacus 3.0 from 2.0, everything seems to be working fine except for this particular error that keeps popping up. I followed the steps provided by SAP team on the documentation site to add the storefinder module. https://i.sstatic.net ...

A guide on harnessing the power of forEach in Ionic 4

I'm currently in the process of upgrading my Ionic v1 app to Ionic 4. Within my app, there is a forEach loop that needs to be adjusted for Ionic 4 compatibility. Here is the code snippet from Ionic v1: angular.forEach(this.selectedQuestion.answers, ...

Is there an option for keyPrefix in i18next?

For my current project, I am utilizing both i18next and react-i18next. One useful feature of using the useTranslation hook from react-i18next is the "keyPrefix" option, which helps in reducing code duplication. However, there are instances where I need to ...