簡體   English   中英

如何調用組件的get function from angular服務?

[英]How to call the get function from angular service to a component?

我一直在學習在硬幣計數器上創建,我在那里創建了一個硬幣計數器服務和兩個組件,一個組件觸發計數器,另一個組件顯示計數器值。

我試過下面的代碼。

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

一個.component.ts

  coin: number = 0;

  constructor(private coinservice: CoinService) {}

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

在上面的代碼中,addTask() 是由單擊按鈕觸發的。 當我嘗試記錄結果(this.coinservice.getCount())時,它提供了正確的結果。 但是當我試圖在另一個組件中調用 function coinservice.getCount() 時,它不起作用。

two.component.ts

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

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

二.組件.html

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

在上面的組件代碼中,我嘗試從服務中調用 function 來顯示one.component.ts觸發的計數結果。 但我得到的結果是“0”。 我想在two.component.ts中接收計數值。 有人可以幫助我了解我該怎么做嗎? 我對 angular 比較陌生。所以任何幫助將不勝感激..

public coin = 0; 應該替換為public coin = new Subject();

並且你可以在任何你想聽他變化的地方subscribe這個值。

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

當您需要簡單地更新值時 - coin.next(10)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM