NGXS,从同一动作调度开始、成功或失败动作的最佳方式?

NGXS, best way to dispatch start, success or failure actions from the same action?

我有以下代码来获取我所有的 posts

`    @Action(actions.FetchPosts)
    fetchAll(ctx: StateContext<PostStateModel>){
        return this.postService.fetchPosts().pipe(tap((postsResults) => {
            const state = ctx.getState();
                ctx.patchState({
                ...state,
                posts: [                    
                    ...postsResults                    
                ],                
            })
        }),
        mergeMap(() => {
          console.log("Inside of mergeMap")
          return ctx.dispatch(new actions.FetchPostsSuccess())
        }),      
        catchError(err => 
        {
          console.log("Inside of catchError")
          return ctx.dispatch(new actions.FetchPostsFail(err))
        }
      ))
    }`

这可行,但是,我想在调用我的 post 服务之前执行另一次调度。使用异步编程确保我首先分派将加载 属性 设置为 true 的开始操作的最佳方法是什么,然后确保我只在请求 return 成功时调用成功。

此外,按照 ngxs 文档,我正在使用 mergeMap() ,它似乎可以完成工作。不过我很好奇,post服务 return 是一个 post 数组 return 一个单独的可观察对象还是一个单独的可观察对象然后发出多个高阶可观察对象(内部可观察量)?

您可以从调度加载操作开始:

@Action(actions.FetchPosts)
fetchAll(ctx: StateContext<PostStateModel>){
    return ctx.dispatch(new ChangeLoadingToInProgress()).pipe(
      mergeMap(() => this.postService.fetchPosts()),
      tap((postsResults) => {
        const state = ctx.getState();
            ctx.patchState({
            ...state,
            posts: [                    
                ...postsResults                    
            ],                
        })
    }),
    mergeMap(() => {
      console.log("Inside of mergeMap")
      return ctx.dispatch(new actions.FetchPostsSuccess())
    }),      
    catchError(err => 
    {
      console.log("Inside of catchError")
      return ctx.dispatch(new actions.FetchPostsFail(err))
    }
  ))
}

或者我相信您可以立即更改状态:

@Action(actions.FetchPosts)
fetchAll(ctx: StateContext<PostStateModel>){
    ctx.patchState({ loading: true });
    return this.postService.fetchPosts().pipe(tap((postsResults) => {
        const state = ctx.getState();
            ctx.patchState({
            ...state,
            posts: [                    
                ...postsResults                    
            ],                
        })
    }),
    mergeMap(() => {
      console.log("Inside of mergeMap")
      return ctx.dispatch(new actions.FetchPostsSuccess())
    }),      
    catchError(err => 
    {
      console.log("Inside of catchError")
      return ctx.dispatch(new actions.FetchPostsFail(err))
    }
  ))
}