Sign up for notifications about updates to a variable within an Angular service

Is there a way to track changes in the value of a variable within an Angular service?

I've been searching for a solution, but haven't been able to find one yet.

In my layout's header component, I have a counter that displays the number of items in the cart. This count is linked to the variable simsInCartLength.

Within my service, I manage adding and removing items from the cart. There's a variable called noSims that stores the current length of the cart item array.

How can I receive notifications when the service variable noSims changes?

Component Code:

simsInCartLength = this.cartService.noSims;

Service Code (the variable updates whenever items are added or removed):

this.noSims = this.simsInCart.length;

Appreciate any help!

Answer №1

To improve the functionality of your service, consider implementing BehaviorSubject in the following way:

private cartItemCount = new BehaviorSubject<number>(0);
cartItem = [];

getCartItemCount(){
   return this.cartItemCount.asObservable();
}

addToCart(obj: any){
   this.cartItem.push(obj);
   // Implement necessary operations to add item to cart and then use next() method of the observable to emit the new value event
   this.cartItemCount.next(this.cartItem.length)
}

// Implement similar code for removeFromCart()


Furthermore, ensure that you subscribe to this event in your component:


ngOnInit(){
  this.cartService.getCartItemCount().subscribe(len => {
     console.log(len) // New length of your cart will be displayed here
     this.simsInCartLength  = len;
  })
}

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

Determine whether the ng bootstrap modal has already been opened

Is there a way to determine if a modal window is open? In order to accomplish this, I create a variable called modalInstance: NgbModalRef; and initialize the modal by using the code below this.modalInstance = this.modalService.open(UpdateModalConten ...

Iterate through the Ionic3/Angular4 object using a loop

I've been attempting to cycle through some content. While I tried a few solutions from StackOverflow, none seem to be effective in my case. Here is the JSON data I am working with: { "-KmdNgomUUnfV8fkzne_":{ "name":"Abastecimento" }, ...

A guide on retrieving bytecode from a specific PDF using Angular

Can anyone help me with extracting the bytecode from a selected PDF file to save it in my database? I keep encountering an error stating that my byte is undefined. Could someone please review my code and identify what might be causing this issue? I attemp ...

Tips for troubleshooting a React Native project built with Expo and utilizing TypeScript

I started a new Expo project with TypeScript integration. After launching the app using expo start, I noticed that the Chrome debugger only displays .js files at http://localhost:19001/debugger-ui/: https://i.stack.imgur.com/cmyy9.png How can I make sur ...

Having trouble with passing data using @Input in Angular 5

My goal is to pass a value from app.component.ts named user and assign it to the property of the userComponent called user. Below are the code snippets: app.component.ts import { Component } from '@angular/core'; @Component({ selector: &apo ...

NPM Package: Accessing resources from within the package

My Current Setup I have recently developed and published an npm package in typescript. This package contains references to font files located within a folder named public/fonts internally. Now, I am in the process of installing this package into an Angul ...

Having trouble importing a TypeScript module from the global node_modules directory

I have a library folder located in the global node modules directory with a file named index.ts inside the library/src folder //inside index.ts export * from './components/button.component'; Now I am trying to import this into my angular-cli ap ...

Build a Node.js application using TypeScript and all necessary dependencies

I've developed a Node.js application using TypeScript and now I'm looking to compile it. Currently, only the source files in the src folder are included in the build. However, I also want to incorporate dependencies such as express, body-parser, ...

How can I populate dropdown options from an API in a react JS project using typescript and react saga?

Check out my page, where I am trying to fetch brand options from an API. Below is the saga I have implemented: Action.tsx export const getBrandsForDropdown = (request: IPagination) => { return { type: actions, payload: request ...

Typescript: Why Lines Are Not Rendering on Canvas When Using a For-Loop

What started out as a fun project to create a graphing utility quickly turned into a serious endeavor... My goal was simple - to create a line graph. Despite my efforts, attempting to use a for-loop in my TypeScript project resulted in no output. In the ...

Adding a tooltip to an Angular Material stepper step is a great way to provide

I am trying to implement tooltips on hover for each step in a stepper component. However, I have encountered an issue where the matTooltip directive does not seem to work with the mat-step element. <mat-horizontal-stepper #stepper> <mat-step lab ...

Angular application automatically adding 'localhost' before the backend API endpoint

After migrating my backend to AWS, the backend URL is functioning correctly in Postman. However, when I use the backend URL in an Angular service, 'localhost' is being added to the front of it. How can I resolve this issue? Backend URL: api.an ...

Transitioning to mui5's sx prop instead of makeStyles is generating a typescript error - none of the overloads match this call when passing an object with

I encountered an issue while converting a component to mui 5. Here is the original code snippet: const useStyles = makeStyles({ imageContainer: { display: "flex", width: "65%", float: "left", marginRight ...

Firebase data not appearing on screen despite using the async pipe for observables

My current challenge involves accessing data based on an id from Firebase, which comes back as an observable. Upon logging it to the console, I can confirm that the Observable is present. However, the issue arises when attempting to display this data on th ...

The TypeScript compiler is indicating that the Observable HttpEvent cannot be assigned to the type Observable

Utilizing REST API in my angular application requires me to create a service class in typescript. The goal is to dynamically switch between different url endpoints and pass specific headers based on the selected environment. For instance: if the environmen ...

Navigating to specific rows in a primeng virtualscroll table using the scrollToIndex

Utilizing Primeng virtual scroll table in Angular to manage large datasets in an array. I am interested in using the scrollToIndex. Is there an equivalent of cdk-virtual-scroll-viewport in Primeng table? I need the functionality where, upon a user clicking ...

Why is my Typescript event preventDefault function ineffective?

Despite all my efforts, I am still unable to prevent the following a tag from refreshing the page every time it's clicked. <p> <a onClick={(e) => handleClick} href="&qu ...

Unable to retrieve rxjs resource

After upgrading to rxjs 5.4.3, I encountered an error in the browser. Despite having "rxjs": "5.4.3" installed in my package.json, I cannot seem to resolve this error message. Here's the content of my ts file: import { Injectable ...

Using constant variables as arguments in functions in TypeScript

While learning about TypeScript, I encountered some confusion regarding how it handles const variables. Let's consider a scenario where I define an interface for a number: interface MyNumber { value: number; } If I then create a constant MyNumbe ...

Set an array to a JSON object as a fresh entity

My challenge involves working with an array that contains certain values. let myArray = [value1, value2]; I am looking to generate a JSON object in the format shown below: { "field": "[value1, value2]" } ...