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

Error message: When using Vue CLI in conjunction with Axios, a TypeError occurs stating that XX

I recently started working with Vue.js and wanted to set up a Vue CLI project with Axios for handling HTTP requests. I came across this helpful guide which provided a good starting point, especially since I plan on creating a large project that can be reus ...

How to activate form autofill in an Angular app

After migrating my app to Angular, I noticed that the form no longer autocompletes upon returning page visits. However, everything else seems to be working perfectly fine. I have a hunch that this issue is related to the *ngIf template expressions and the ...

How can we prevent new chips (primeng) from being added, but still allow them to be deleted in Angular 2?

Hey there! I'm currently exploring how to make the chips input non-editable. I am fetching data objects from one component and using the keys of those objects as labels for the chips. Check out my HTML code below: <div class="inputDiv" *ngFor="le ...

Using SignalR to implement CRUD operations within a Hub or Controller

I have been working on an Angular app that is built on top of an ASP.NET MVC application. In this project, I have a Dashboard where I showcase Average and Total numbers that are altered during Create / Update / Delete events. Usually, these events are hand ...

Every time I try to run my Angular app, it crashes. I've already tried reinstalling Node and rebooting

After attempting to relocate an angular project into a different folder yesterday, I encountered issues when trying to start the app using ng serve. Interestingly, creating a new project and running ng serve resulted in the same error. Both projects were ...

What is the best way to scroll a specific element within a div container?

I need to enable horizontal scrolling on the user-selected content within a specific div by utilizing its ID. Here is the HTML code snippet: <ion-scroll #scroll scrollX="true" style="height:85px; border-bottom: 2px solid #a01e1e;"> <div class="s ...

The data type 'Observable<{}[]>' cannot be matched with the type 'AngularFireList<any>'

I have been learning how to use AngularFire2 by following this tutorial. Encountered the error: 'Type 'Observable<{}[]>' is not assignable to type 'AngularFireList'. Property 'query' is missing in type 'Obse ...

Error in Angular: Trying to access the property 'id' of an undefined value

I am facing an issue with a div tag in my HTML file. The code snippet looks like this: <div *ngIf="chat.asReceiver.id != user?.id; else otherParty"> Unfortunately, it always returns the following error: ERROR TypeError: Cannot read propert ...

How to retrieve the displayed text of a selected option in an Angular 7 reactive form dropdown control instead of the option value

Is there a way to retrieve the displayed text of the selected value in a drop-down list instead of just the value when using reactive forms? This is my current script: <form [formGroup]="formGroup" formArrayName="test"> <ng-container matColu ...

Tips for sorting/merging/consolidating data in Angular

Take a look at this code snippet: rowData = [ [ '2019-12-10 08:00:00', '2019-12-10 08:00:00', '2019-12-10 08:00:00', '2019-12-10 08:00:00', '2019-12-10 08:00:00', '2018-12-10 08:00:00' ...

Having trouble with sending values to Angular 7 components' HTML pages

Struggling with a simple task and encountering an error: Code snippet below: app.component.html <div class="col-md-{{myvalue}}">stuff here</div> app.component.ts myvalue: string; ngOnInit() { this.myvalue('6'); } Seeing th ...

Troubleshooting Angular2: SVG Disappearing Upon Page Reload with PathLocationStrategy

I encountered a strange problem with SVG while using Angular2's PathLocationStrategy. The SVG code in my HTML template looks like this: <svg class="bell__icon" viewBox="0 0 32 32"> <use xlink:href="#icon-notificationsmall"></use&g ...

Encountering this issue: Unable to access the property 'length' of an undefined variable

I'm currently developing an app using nuxt, vuetify 2, and typescript. Within the app, I have radio buttons (referred to as b1 and b2) and text fields (referred to as t1, t2, t3). When a user clicks on b1, it displays t1 and t3. On the other hand, w ...

Uploading Files with Angular 2 using AJAX and Multipart Requests

I am currently working with Angular 2 and Spring MVC. At the moment, I have an Upload component that sends an AJAX request to the Spring backend and receives a response containing parsed data from a .csv file. export class UploadComponent { uploadFile: f ...

Angular form: Choose an option by selecting it and clicking on a button

I need help with my Angular form. I want to allow users to select a value when they click on a button. How can I achieve this? page.html <div *ngFor="let product of products; index as i"> <button (click)="chooseProduct(i)">{{product.name} ...

What is the best way to remove a polygon from an agm-map?

Is there a way to remove a polygon from the map when the clear button is clicked? <agm-map [latitude]="40.034989" [longitude]="29.062844" [zoom]="15" [agmDrawingManager]="drawing" class="full-width-height"> ...

Since transitioning my project from Angular 7.2 to Angular 8, I noticed a significant threefold increase in compile time. How can I go about resolving this issue

After upgrading my project to Angular 8, I noticed a significant increase in compile time without encountering any errors during the upgrade process. Is there a way to restore the previous compile time efficiency? **Update: A bug has been identified as th ...

Determining function return property type in Typescript by mapping interface argument property

In order to manage messaging between the browser and a web worker, I have developed a generic class. Each side creates a class that can send specific messages and acknowledge them on the other side with a returned result in a payload. The implementation is ...

Employ a type as a function in Typescript programming

Looking for a way to convert an ID into an object using a specific type. The type accepts personId as a string parameter and returns either a Person or undefined. export type FindPerson = (personId: string) => Person | undefined; I have multiple person ...

Ways to ensure the React prop type matches the value provided when using typescript?

Within my List component, there are 2 props that it takes in: items = an array of items component = a react component The main function of the List component is to iterate over the items and display each item using the specified component. // List ...