Home > Blockchain >  How to call the get function from angular service to a component?
How to call the get function from angular service to a component?

Time:11-21

I have been learning to create on a coin counter, where I have created a service for coin counter and two components, one component to trigger the counter and another to display the counter value.

I tried the below code.

coin.service.ts

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;
  }
}

one.component.ts

  coin: number = 0;

  constructor(private coinservice: CoinService) {}

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

In the above code, the addTask() is triggerd by a button click. and when I tried logging the result(this.coinservice.getCount()), it provides the right result. But when I tried to call the function coinservice.getCount() in another component, it doesnt work.

two.component.ts

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

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

two.component.html

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

In the above component code, I tried to call the function from the service to display the result of the count triggered by one.component.ts. But the result I get is '0'. I would like to receive the count value in the two.component.ts. Can someone help me understand how I can do this? I am relatively new to angular. So any help would be appreciated!.

CodePudding user response:

public coin = 0; should be replaced with public coin = new Subject();

and you can subscribe to the value everywhere you want to listen to his changes.

coinService.coin.subscribe(val => {
  // do what you need with the value
})

when you need to update the value simply - coin.next(10)

  • Related