比方说,我们处于一个状态,可以处理新列表的创建:
@Action(CreateList)
async createList(
ctx: StateContext<StateModel>,
{ payload }: CreateList
) {
// Create a new list
const newList = await this._listServiceProxy
.create(payload.listId, payload.input)
.toPromise();
ctx.setState(
patch<StateModel>({
lists: append([newList])
})
);
}
假设我们需要已创建列表的新ID。
当前,动作调度仅返回一个可观察到的动作,该动作在动作完成后将接收新状态。在这种情况下,获取最后一个列表是可行的,但是根据用法来找到变通方法并不总是那么容易。
如何发回创建的列表ID?
答案 0 :(得分:0)
根据我在NGXS官方松弛频道上获得的答案,从动作分派返回值是一种反模式。因此提供了以下解决方案(感谢@poloagustin!):
动作:
@Action(CreateList)
createList(
ctx: StateContext<StateModel>,
{ payload }: CreateList
) {
// Creation logic
return ctx.setState(
patch<StateModel>({
lists: append([newList]),
newIds: patch({[payload.listId]: newList.map(({id}) => id)})
})
);
}
在组件中:
const postCreateListOperationsSubscription = this.actions.pipe(ofActionSuccessful(CreateList), tap(({payload}) => {
const newIds = this.store.select(state => state.app.newIds[payload.listId]);
}))