[英]How to call the get function from angular service to a component?
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 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一个.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.在上面的代码中,addTask() 是由单击按钮触发的。 and when I tried logging the result(this.coinservice.getCount()), it provides the right result.
当我尝试记录结果(this.coinservice.getCount())时,它提供了正确的结果。 But when I tried to call the function coinservice.getCount() in another component, it doesnt work.
但是当我试图在另一个组件中调用 function coinservice.getCount() 时,它不起作用。
two.component.ts two.component.ts
public coom : number =1;
constructor(private coinservice: CoinService) { }
ngOnInit(): void {
this.coom = this.coinservice.getCount();
}
two.component.html二.组件.html
<img class="coinCount" 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 .在上面的组件代码中,我尝试从服务中调用 function 来显示one.component.ts触发的计数结果。 But the result I get is '0'.
但我得到的结果是“0”。 I would like to receive the count value in the two.component.ts .
我想在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..
我对 angular 比较陌生。所以任何帮助将不胜感激..
public coin = 0;
should be replaced with public coin = new Subject();
应该替换为
public coin = new Subject();
and you can subscribe
to the value everywhere you want to listen to his changes.并且你可以在任何你想听他变化的地方
subscribe
这个值。
coinService.coin.subscribe(val => {
// do what you need with the value
})
when you need to update the value simply - coin.next(10)
当您需要简单地更新值时 -
coin.next(10)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.