英文:
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()
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论