Home > Net >  How to use angular services to pass count value to the Component?
How to use angular services to pass count value to the Component?

Time:11-21

I have been trying to develop a coin counter for my application and for the purpose, I created a service for counter and tried to use it in one of my component where the counter function is trigged. But I have been struggling to use the service inside my component. I would really appreciate some help to understand how to use my service inside the component

Below is the code I tried

coin.service.ts

import { Injectable } from '@angular/core';
@Injectable({
  providedIn: 'root'
})

export class CoinService {
   public coin =0;

setCount(coinValue:number){
  this.coin = coinValue; 
}

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

}

one.component.ts

export OneComponent implements OnInit(){

  coin :number = 0;
  constructor(private coinservice: CoinService) {}
  ngOnInit(): void {}

  addTask(){
    this.coinservice.setCount(this.coin);
    console.log('coin:',this.coin);
    this.coinservice.getCount();
  }
  }

In the above code for the component , the addTask() is trigged by button click. So on button click, i want to increment the counter, But the current code logs " coin: 0" I understand I didnt use the service in the right way inside my component. Can someone show me how to use it in a proper way to get the count value . Thank you in advance!

CodePudding user response:

It's hard to fully tell what you're aiming to do; however, it looks like you're using the coin service correctly. The issue, though, is that you're not actually adding anything currently (this.coin is set to 0 inside the component). Let's try adding a nickel:

export OneComponent implements OnInit(){

  coin: number = 5;

  constructor(private coinservice: CoinService) {}

  ngOnInit(): void {}

  addTask(){
    this.coinservice.setCount(this.coin); 
    // The total is tracked in the coinservice
    console.log('coin:',this.coinservice.getCount());
  }
}
  • Related