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!