如何使用angular服务将count值传递给组件?



我一直在尝试为我的应用程序开发一个硬币计数器,为此,我创建了一个计数器服务,并试图在触发计数器功能的组件之一中使用它。但是我一直在努力使用组件内的服务。如果能帮助我理解如何在组件

中使用我的服务,我将非常感激。下面是我试过的代码

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

在上面的组件代码中,addTask()是由单击按钮触发的。所以点击按钮,我想增加计数器,但是当前的代码记录"硬币:0">我知道我没有在组件中正确地使用服务。有人能告诉我如何使用它在一个适当的方式来获得计数值。提前感谢!

很难完全说出你的目标是什么;不过,看起来你使用投币服务是正确的。但问题是,您目前实际上没有添加任何内容(组件内的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());
}
}

最新更新