gpt4 book ai didi

angular - NGXS:有没有办法在一个 Action 完成后返回一个特定的值

转载 作者:行者123 更新时间:2023-12-04 15:20:16 25 4
gpt4 key购买 nike

假设我们有一个处理新列表创建的 state Action :

@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。
目前, Action 分派(dispatch)只返回一个在 Action 完成后接收新状态的可观察对象。在这种情况下获取最后一个列表是有效的,但根据使用情况,找到解决方法并不总是那么容易。
如何发回创建的列表 ID?

最佳答案

根据我在 NGXS 官方 slack channel 上得到的答案,从 Action 调度中返回一个值是一种反模式。因此提供了以下解决方案(感谢@poloagustin!):

  • 也将列表 ID 存储在状态中。
  • 在创建时将其添加到列表数组后,将新创建的列表的 Id 推送给它。
  • 使用 Action 的生命周期来检测 Action 分派(dispatch)的结束。
  • 使用选择器获取 ids 的数组。

  • 那个行动:
    @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]);
    }))

    关于angular - NGXS:有没有办法在一个 Action 完成后返回一个特定的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63463155/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com