What is the best way to access the get function in an Angular service from a component?

I have recently been exploring how to create a coin counter feature using Angular. I managed to develop a service for the coin counter and two components: one to increment the counter and another to display the counter value.

Below is the code snippet I worked on:

CoinService

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

@Injectable({
  providedIn: 'root',
})

export class CoinService {
  
  public coin = 0;

  setCount() {
    this.coin = this.coin + 10;
  }

  getCount(): number {
    return this.coin;
  }

  decrementCount() {
    this.coin = this.coin - 10;
  }
}

OneComponent

coin: number = 0;

constructor(private coinservice: CoinService) {}

addTask() {
if (this.onAddItem) {
this.coinservice.setCount();
console.log('Coin count:', this.coinservice.getCount());
}
}

In the provided code, the addTask() function is activated by a button click. When I tested logging the result (this.coinservice.getCount()), it returned the correct value. However, when attempting to call coinservice.getCount() in another component, it does not work as expected.

TwoComponent

public coom : number =1;
constructor(private coinservice: CoinService) { }

ngOnInit(): void {
this.coom = this.coinservice.getCount();
}

two.component.html

<img class="coinCount" src="assets/images/coin.png" width="10px" height="10px"> {{coom}}

In the above component code, I attempted to retrieve the count value triggered by OneComponent through the service in order to display it in TwoComponent. Unfortunately, the displayed result was '0'. I am looking for guidance on how to appropriately access the count value in TwoComponent.ts. As a newcomer to Angular, any assistance would be highly appreciated!

Answer №1

initially set coin = 0; is to be replaced with

initialize coin as new Subject();

then, you can register for updates wherever you wish to track its modifications.

coinService.coin.subscribe(value => {
  // perform actions based on the value
})

whenever an update is needed, simply use - coin.next(10)

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

Passing asynchronous data to child components using an object in Angular6

Currently, I am facing an issue with displaying data retrieved from a server using Angular 6, Rxjs, and Chartjs. When utilizing local mock data, everything works perfectly fine. However, when fetching data from the server, the charts render as blank becaus ...

Verifying the Loading of a Module in Angular 5

I am working on Angular 5 and I am trying to figure out how to determine if a module has been loaded already so that I can avoid displaying the spinner unnecessarily. Currently, this is my code: constructor(private loaderService: LoaderService, private ro ...

Using React with Firebase: Retrieving User Data through UID

Hello everyone, I'm in need of some help. I have the UID and am trying to retrieve user data from Firebase. Is there a way to do this that someone could kindly guide me through? I'm working with React and am not sure how to proceed. Thank you in ...

Is there a way to show uppercase values in Angular's tooltip as capital letters?

Here is my HTML code: <i [class]="item.icon" [pTooltip]="item.item" tooltipPosition="bottom" ></i> The value inside item.item is 'ATTACHMENT' and I am unable to modify it from the ts file. Is there a way ...

Display the notification list by utilizing the "ToastController" function

Upon entering the home screen, I want to notify the user by displaying a list of messages from a firebase collection. The field to be displayed is "text", but I only want to show messages with the "read" field set as false. Once a message is shown, its "re ...

Testing the unit with a customized header in the interceptor

I've been struggling to execute a unit test within an Angular 6 interceptor, but despite numerous attempts, I keep encountering the following error: Error: Expected one matching request for criteria "Match by function: ", found none. I'm rela ...

Handling ASP.net POST requests in Angular2

Here is a method called gotoDispatch: gotoDispatch() { // const headers = new Headers(); headers.append('Content-Type', 'application/json'); var url = 'Users/Cards'; var dto = { 'jsonSearchCards&apo ...

Transferring data between arrays in TypeScript depending on a specified condition

I am looking to transfer all data from one array to another in TypeScript based on a certain condition. array: any = [ { Hostname: 'CBA', Certificate_Expiry_Date: ...

Integrate worldwide sass into Angular 4 using webpack

I'm facing an issue with my Angular 4 project that uses webpack with HMR. Just to note, I am integrating it with ASP Core 2 using the angular template. My goal is to create a global/main SCSS file that will be applied to all components. I want this S ...

Angular 6 methods that handle Observable data from HTTP GET requests complete execution before constructing the final Data

My goal is to retrieve data from a REST endpoint and then construct a List of instances to return. However, I'm facing an issue where the HTTP GET function returns an Observable method that always results in an empty list before populating it with dat ...

ReactJS: A single digit input may result in the display of numerous '0's

My goal is to have a small box that only allows one digit, but it seems to work fine until I try to input multiple '0's. Then the box displays multiple 0000 persistently. https://i.sstatic.net/Ouot4.png https://i.sstatic.net/MMKjm.png H ...

What is the reason behind installing both Typescript and Javascript in Next.js?

After executing the command npx create-next-app --typescript --example with-tailwindcss my_project, my project ends up having this appearance: https://i.stack.imgur.com/yXEFK.png Is there a way to set up Next.js with Typescript and Tailwind CSS without i ...

Guide to resolving a Promise that returns an array in TypeScript

My goal is to retrieve an array in the form of a promise. Initially, I unzipped a file and then parsed it using csv-parse. All the resulting objects are stored in an array which is later returned. Initially, when I tried returning without using a promise, ...

How to center text in MatButtonToggle within angular material?

I'm facing a challenge in customizing the MatButtonToggle as I am having issues with centering the label: https://i.sstatic.net/LVzrm.png Here is the template for reference: <mat-button-toggle-group name="condition" aria-label="Condition"> ...

Evaluate compatibility across different browsers within a single test scenario utilizing protractor

Looking to experiment with testing a chat application, I'm curious about running one instance of Chrome alongside another instance of Firefox to send messages between the two. After researching, it seems I can open multiple browser sessions for the sa ...

Encountering a NaN outcome when summing values from various select options

I'm working on a project that involves adding up the prices based on the surface chosen by the user. I'm struggling with calculating the partial cost when the user's choice changes. totalSum.ts num: Calculation totalAmount: number cate ...

Dealing with a 404 Error in Instagram API Using RXJS

Utilizing the Instagram API without OAuth involves using this URL: https://www.instagram.com/explore/tags/{tag}?__a=1 Everything works smoothly, I successfully obtain and manipulate the JSON data. However, when a non-existing tag is used, I encounter a 40 ...

having difficulties sorting a react table

This is the complete component code snippet: import { ColumnDef, flexRender, SortingState, useReactTable, getCoreRowModel, } from "@tanstack/react-table"; import { useIntersectionObserver } from "@/hooks"; import { Box, Fl ...

Pass the identical event to multiple functions in Angular 2

On my homepage, there is a search form with an input box and select dropdown for users to search for other users by location or using html5 geolocation. When a user visits the page for the first time, they are prompted to allow the app to access their loca ...

Why does Angular perform a full tree check during local changes in change detection?

Imagine a scenario where there is a straightforward array of texts: contentList = [ {text: 'good morning'}, {text: 'lovely day'}, {text: 'for debugging'}, ] A simple component is rendered for each item in the a ...