Using Angular 7 shared service to allow sibling components to exchange data between each other

In my Angular 7 application, I have two sibling components - a configurator component and a custom stepper component. The configurator component is responsible for fetching data from the API and performing calculations on it. I would like to display the calculated values in the custom stepper component.

I have created a service called PriceWeightService but I am unsure about which code should be moved where and how to retrieve the values from that service in the custom stepper component.

The configurator.component.ts contains the following code:

 //Code from configurator component
//...

The custom-stepper.component.ts file contains the following code:

// Code from custom-stepper component
// ...

This is the HTML for the custom stepper component where I want to display the values:

// HTML code for displaying values in custom stepper component
// ...

I have included the PriceWeightService in the project with the following code:

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

@Injectable({
  providedIn: 'root',
})
export class PriceWeightService {
  weight = 0;
}

Answer №1

Define attributes within the service:

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

@Injectable({
  providedIn: 'root',
})
export class ProductDetailsService {
  quantity = 0;
}

Inject the service into both modules

constructor(private productDetails: ProductDetailsService){}

Assign a value to the service attribute from your configurator component as shown below

this.productDetails.quantity = this.getTotalQuantity();

Services act as singletons, so any changes made will reflect in other components using the service.

To access the service attribute in your step component, either make the service public or create a getter method.

constructor(public productDetails: ProductDetailsService){}
<p>{{productDetails.quantity}}</p>

or

constructor(private productDetails: ProductDetailsService){}

get quantity(){
  return this.productDetails.quantity;
}
<p>{{quantity}}</p>

The specific code snippet you require

service

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

@Injectable({
  providedIn: 'root',
})
export class ProductDetailsService {
  price = 0;
  quantity = 0;
}

configurator.component.ts

this.httpClient.get(`${environment.apiUrl}`, httpOptions).subscribe(
            (data) => {
                this.parseData(data);
                console.log('Selected:', this.selected);
                this.productDetailsService.quantity = this.getTotalQuantity();
                this.productDetailsService.price = this.getTotalPrice();
            },
            (error) => {
                console.log('Error', error);
            }
        );

custom-step.component.ts

  constructor(private productDetails: ProductDetailsService){}

  get totalQuantity(){
    return this.productDetails.quantity;
  }

  get totalPrice(){
    return this.productDetails.price;
  }

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

Altering the character by striking a key

I have a canvas with custom styling. In the center of the canvas is a single letter. Please see the code below for reference. The goal is to change the displayed letter by pressing a key on the keyboard. For instance: Letter A is centered in the canvas: P ...

What is the best way to include JSX in a separate HTML file?

Currently developing a PWA using create-react-app. Upon inspecting the index.html page, I realized there are no links to any JS files, leading me to assume that CRA injects JSX into the 'root' div of index.html. Now, my goal is to include an offl ...

Simultaneous malfunction of two ajax forms

I have a dilemma with two boxes: one is called "min amount" and the other is called "max amount." Currently, if I input 100 in the max amount box, it will display products that are priced at less than $100. However, when I input an amount like $50 in the m ...

Question from a student: What is the best way to transfer information between different classes?

Currently, I am delving into SPFX development. My focus is on constructing a form that incorporates multiple classes in order to gain insight on how they can interact and share data among one another. In this scenario, I have established two distinct clas ...

Looking for assistance in establishing a connection between Node.js and Angular.js

I have a decent understanding of mongodb and node.js, but I'm struggling with angular.js. I need some help in figuring out how to retrieve data from my node.js code using angular.js. If there are any errors in my node.js code, please let me know. var ...

VueJS 3 is in the process of loading dynamic assets

I am facing an issue with loading and displaying images dynamically from the assets folder in my Vue.js project. The code I have written does not seem to work as expected: <img :src="getSource(data.thumbnail)" :alt="data.name"/> ...

Flipping and rotating images using the power of HTML5 Canvas

Hello, I need assistance with my Electron app that arranges images for batch printing on an industrial printer. The issue I am facing is with images flipping or being mirrored unpredictably. Below is the code snippet responsible for determining whether an ...

Tips for successfully passing a ViewBag in ng-click

<th><a href="javascript:;" ng-click="order(@ViewBag.desc)">Name</a></th> I am currently implementing this code and trying to fetch data from the view bag into my Angular Controller. However, I seem to be facing some challenges in a ...

Preventing autoscrolling in Ionic's dual side menu template when additional content is added

Could anyone kindly assist me in figuring out why the autoscrolling of the content is not functioning correctly? Whenever the button on the header is clicked, a new message will be included in the main content. However, once the number of lines exceeds wha ...

TypeScript does not automatically determine the type of a passed generic parameter

I am currently working on defining flexible types for my api responses, but I am struggling to find the right approach for type conversion using TypeScript 4.5.4. My goal is to parse the response and determine the type that will be used later in the code. ...

Combining the power of AngularJS with the versatility of sails

A project I'm working on involves utilizing sails.js for back-end and AngularJS for front-end. My plan is to use the Yeoman-angular generator https://github.com/yeoman/generator-angular to create the Angular app first. Once the front-end development i ...

When attempting to compress JavaScript with uglify-js, an unexpected token error occurs with the symbol ($)

When attempting to compress Bootstrap 4 js file using uglify-js, I encountered an error. The error message reads as follows: "Parse error at src\bootstrap\alert.js:1,7 import $ from 'jquery' ERROR: Unexpected token: name ($)". Now I am ...

A helpful tip on incorporating Snack Bar Material UI within an if statement

When my Camera Component encounters an error, I want to display a snackbar notification. I attempted to encapsulate the component within a function and pass the error message as props, calling it in the if statement. However, this approach did not work as ...

Establishing default parameters for angular pipes

Is there a way to establish default settings for an angular pipe without creating a custom one myself? I frequently utilize the currency pipe in this manner {{ price | currency:'EUR':'symbol':'0.2-2':'de' }} I&apo ...

Exploring the getJSON function within jQuery

{ "Emily":{ "Math":"87", "Science":"91", "Email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1d6f7e767c51767b727e737f764f747879">[email protected]</a>", "City":"Chicago" }, "Sa ...

Using the mt-downloader module in a Node application is a straightforward process

Hey there, I'm looking to incorporate the Multi downloader module into my project. I've checked out the GitHub link, but unfortunately, there are no examples provided on how to actually use this module. I came across this example and tried implem ...

Angular2: The provided arguments do not correspond to any valid call signature

I have developed my own Observable service implementation import { Injectable, EventEmitter, Output} from '@angular/core'; @Injectable() export class CustomObservableService { data = []; @Output eventEmitter:EventEmitter = new EventEmit ...

How to resolve the error of "Cannot GET /api/courses/1"

const express = require('express'); const app = express(); app.get('/',(req,res) =>{ // viewable at localhost:3000 res.send('hello world'); }); app.get('/api/courses',(req,res) =>{ // shown on ...

Issue with regex replacement behaving differently in Node compared to console

I am having trouble properly escaping commas in a sentence. Oddly enough, my replace method is not functioning correctly in node, while it works fine in the Chrome console. Is there anyone who has a solution to this issue? It seems to be occurring with al ...

Retrieve the chosen option from a dropdown menu and transfer it to the submit button in PHP

I have a unique situation where I need to extract and store selected values from two separate drop-down menus generated from arrays. The goal is to pass these selected values in the submit button link. For example, if a user selects "123" for email and "t ...