Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use angular services to pass count value to the Component?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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());
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading