我一直在嘗試為我的應用程式開發一個硬幣計數器,為此目的,我創建了一個計數器服務,并試圖在我的一個組件中使用它來觸發計數器功能。但是我一直在努力使用組件內部的服務。我真的很感激一些幫助,以了解如何在組件內使用我的服務
下面是我試過的代碼
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;
}
}
一個.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();
}
}
在上面的組件代碼中,addTask() 是通過單擊按鈕觸發的。所以在單擊按鈕時,我想增加計數器,但是當前代碼記錄“硬幣:0”我知道我沒有在我的組件中以正確的方式使用該服務。誰能告訴我如何以正確的方式使用它來獲取計數值。先感謝您!
uj5u.com熱心網友回復:
很難完全說出你打算做什么;但是,看起來您正在正確使用投幣服務。但是,問題是您當前實際上沒有添加任何東西(this.coin設定0在組件內部)。讓我們嘗試添加鎳:
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());
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/537231.html
標籤:有角度的打字稿角度服务
