【问题标题】:NgRx Effect dispatch multiple events after calling service with data from payload arrayNgRx Effect 在使用有效负载数组中的数据调用服务后调度多个事件
【发布时间】:2018-12-06 04:35:03
【问题描述】:

我有一个用户列表,我需要获取每个用户的角色。

所以我有一个动作 LoadUserRole 需要一个用户数组:

export class LoadUserRole implements Action {
  readonly type = UsersActionTypes.LoadUserRole;

  constructor(public payload: Array<User>) {}
}


export class LoadUserRoleSuccess implements Action {
  readonly type = UsersActionTypes.LoadUserRoleSuccess;

  constructor(public payload: { user: Update<User> }) {}
}

我正在使用 NgRx Effects 来处理调用服务的副作用:

 // Side Effect of the load users action
  @Effect()
  loadUserRole$ = this.actions$.pipe(
    ofType(UsersActionTypes.LoadUserRole),
    map((action: LoadUserRole) => action.payload),
    filter(users => users.length !== 0),
    map((users: User[]) => users.map((user: User) => user.id)),
    concatMap((ids: string[]) => ids.map((id: string) =>
        this.accountService
          .getAccountRole(id)
          .pipe(
            map((asset: any) => new LoadUserRoleSuccess({
              user: {
                id: asset.items[0].userId,
                changes: {
                  roleType: asset.items[0].roleType
                }
              }
            })),
            catchError(error => {
              return of(new LoadUserRoleFailure(error.message));
            })
          )
        )
      )
  );

根据 NgRx Entity 的 Entity Adapter,赋予 LoadUserRoleSuccess 的对象是 Update 类型。所以 LoadUserRoleSuccess 更新状态中的用户,这在我用一个用户测试时有效。

但是这段代码给了我错误:

ERROR Error: Effect "UsersEffects.loadUserRole$" dispatched an invalid action: [object Object]

ERROR TypeError: Actions must have a type property

帐户服务很好地一次记录每个 id,但由于某种原因成功的调度不起作用,服务中也没有调用后端。

处理这种情况的最佳方法是什么?

这是我的减速器功能:

case UsersActionTypes.LoadUserRole: {
  return {
    ...state,
    pending: true,
  };
}

case UsersActionTypes.LoadUserRoleSuccess: {
  return usersAdapter.updateOne(action.payload.user, {
    ...state,
    pending: false,
  });
}

【问题讨论】:

  • 你的LoadUserRoleSuccess是什么样的?
  • export class LoadUserRoleSuccess implements Action { readonly type = UsersActionTypes.LoadUserRoleSuccess; constructor(public payload: { user: Update&lt;User&gt; }) {} }
  • 只是一个想法,但也许只需将concatMap 替换为mergeMap 即可解决
  • 不,同样的错误,感谢您的评论
  • 你能分享你的动作类型定义吗

标签: angular typescript rxjs ngrx ngrx-effects


【解决方案1】:

既然你在那里使用地图,试试这个:


 map((asset: any) => of(new LoadUserRoleSuccess({
              user: {
                id: asset.items[0].userId,
                changes: {
                  roleType: asset.items[0].roleType
                }
              }
            }))),

of 将确保它将作为可观察对象而不是对象返回

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-28
    • 1970-01-01
    • 2018-11-10
    • 2020-04-04
    • 1970-01-01
    • 2020-11-18
    • 2018-05-11
    • 2019-12-29
    相关资源
    最近更新 更多