如何更改BehaviorSubject中的值?

huangapple go评论68阅读模式
英文:

How change emmeted value BehaviourSubject?

问题

大家!
我需要清晰的 Emmet 值,例如简单的 BehaviorSubject:
在模板中我有:

{{box}}

//==///

box.subscribe();

box.next(100);// box 显示 100

if(a==5){ box.next(500);}// box 变为 500,显示 500

需要在组件的模板中更改 box 的值。
原来是 100,如果 a 变成 5,就需要将 100 更改为 500。

如何实现?

英文:

everyone!
I need clear emmeted value, example Simple BehaviorSubject:
In template I have:

{{box}}

//==///

box.subscribe();

box.next(100);// box show 100

if(a==5){ box.next(500);}// box changed on 500, show 500

Need in template of component change value box.
Was 100, if a becom 5, 100 need change on 500.

How it can do?

答案1

得分: 1

The provided code segment translates to:

"执行 box.subscribe(); 不会产生任何效果。你必须对订阅进行操作。

boxValue = 0;

ngOnInit(){
  this.box.subscribe(res => {
    console.log('收到数值: ', res);
    this.boxValue = res; // 监听 box 订阅并执行操作
  });
}

然后在模板中你可以使用: {{boxValue}}。

在 .ts 文件中订阅是不良实践,所以可以删除 box.subscribe(); 并使用异步管道:https://angular.io/api/common/AsyncPipe

<h1> Box 值: {{ box | async }} </h1>
```"

<details>
<summary>英文:</summary>

doing `box.subscribe();` won&#39;t do anything. you have to do something with the subscription.
```ts
boxValue = 0:

ngOnInit(){
  this.box.subscribe(res =&gt; {
    console.log(&#39;got a value: &#39;, res);
    this.boxValue = res; // listen to the box subscription and do something
  });
}

then in the template you can do: {{boxValue}}.

subscribing in the .ts file is a bad practice, so instead just delete box.subscribe(); and use the async pipe: https://angular.io/api/common/AsyncPipe

&lt;h1&gt; The box value: {{ box | async }} &lt;/h1&gt;

huangapple
  • 本文由 发表于 2023年3月31日 02:28:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/75891757.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定