Angular 16 信号副作用

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

Angular 16 signals side effects

问题

在信号出现之前,我有一个可观察对象,我会观察它以触发 FormControl 的可编辑属性,就像这样:

this.#isItEditor$
    .pipe(takeUntilDestroyed(this.#destroyRef))
    .subscribe(x => {
        const funded = this.formGroup.controls.funded
        if (x)
            funded.enable()
        else
            funded.disable()
    })

现在我已经从可观察对象改为使用信号,但在这种情况下,似乎我仍然需要从信号创建一个可观察对象,然后以与以前相同的方式执行 pipe/subscribe

我不是基于信号的变化来分配任何东西,我只是在实现一个副作用。这样正确吗?

英文:

Before signals, I had an observable that I would watch to trigger a FormControl's editable property, like this:

this.#isItEditor$
    .pipe(takeUntilDestroyed(this.#destroyRef))
    .subscribe(x => {
        const funded = this.formGroup.controls.funded
        if (x)
            funded.enable()
        else
            funded.disable()
    })

Now I've changed from an observable to a signal, but it feels like, in this case, I still need to create an observable from the signal to then do the pipe/subscribe the same way I used to.

I'm not assigning anything based on the signal changing, I'm just implementing a side effect. Is this correct?

答案1

得分: 0

你可以使用 effect 监听信号变化。effect 会追踪信号读取,每当值发生变化时,effect 会再次运行。

英文:

You could use effect to listen signal changes. Effect will track signal reads and whenever value changes effect runs again.

effect(() => {
  this.#isItEditor(); //Read signal here
  //Rest of the logic
    const funded = this.formGroup.controls.funded
    if (x)
        funded.enable()
    else
        funded.disable()
  
});

huangapple
  • 本文由 发表于 2023年5月10日 20:09:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76218251.html
匿名

发表评论

匿名网友

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

确定