【问题标题】:NGXS: Is there a way to return a specific value after an action is completedNGXS:有没有办法在一个动作完成后返回一个特定的值
【发布时间】:2020-12-07 07:34:58
【问题描述】:

假设我们有一个状态动作来处理新列表的创建:

@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 完成后接收新状态的 observable。在这种情况下获取最后一个列表是可行的,但根据使用情况找到解决方法并不总是那么容易。

如何发回创建的列表 ID?

【问题讨论】:

  • 在函数中返回你需要的值。可以订阅 dispatch action 获取返回数据
  • @AjanthaBandara 我试过这样做,但是调度本身的订阅总是返回新状态,而对ofActionSuccessful动作生命周期的订阅总是返回动作有效负载

标签: angular ngxs


【解决方案1】:

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

  1. 将列表 ID 也存储在状态中。
  2. 在创建时将新创建的列表的 ID 添加到列表数组后,将其推送给它。
  3. 使用动作的生命周期来检测动作分派的结束。
  4. 使用选择器获取 id 的数组。

行动:

@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]);
}))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-23
    • 2020-05-05
    • 1970-01-01
    相关资源
    最近更新 更多