ngrx/component-store 状态改变时触发效果
我有一个带有@ngrx/component-商店的Angular应用
。
当用户从设备列表中选择一个条目时,我现在将其存储到组件商店
component.ts:
onDeviceClicked(device: DeviceTO) {
this.inspectionStore.setDeviceSelected(device);
}
inspectionStore.ts
readonly setDeviceSelected = (data: DeviceTO) => {this.patchState({selectedDevice: data})};
现在,用户已经选择了设备,应触发副作用。但是,我不确定当状态的一部分变化时,如何触发副作用。
更新状态时我需要这样做吗?
readonly setDeviceSelected = (data: DeviceTO) => {
this.patchState({selectedDevice: data});
this.tiggerMySideEffect(data);
};
还是我可以告诉副作用聆听更改的另一种方式?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于效果是自动订阅的,因此不需要外部触发器(通过显式调用效果)。效果可以直接对状态变化做出反应。因此,以下内容(作为示例)确实有效:
此处可以使用任何可观察的内容(例如
this.store
或与combineLatest
的组合等)。更进一步,您可以拥有一系列效果(从外部隐藏) - 对先前效果执行的状态更改做出反应以优化数据(对后端进行不同的调用)。
它们都不需要明确的手动触发。
Since an effect is automatically subscribed to, one does not need an external trigger (by calling the effect explicitly). The effect can directly react to the state-change. So the following (as an example) does work:
Any observable can be used here (e.g.
this.store
or a combination withcombineLatest
, etc).To go a step further, you could have a chain of effects (hidden from the outside) - that react on state-changes performed by a previous effect to refine data (doing different calls to backends).
None of them would need an explicit, manual trigger.
您可以在更新状态后立即从OnDeviceClick中发射效果。
具有类似情况的示例:
指南: https://next.ngrx.io/guide/guide/component-store/usage
You can fire the effect from onDeviceClicked right after updating the state.
Example with a similar case: https://next.ngrx.io/generated/live-examples/component-store-slide-toggle/stackblitz.html
Guide: https://next.ngrx.io/guide/component-store/usage
示例代码
选择器:
订阅:
然后您可以在效果内触发状态更改,如下所示
Sample code
Selector:
Subscription:
Then you can trigger state change inside an effect like this