ngrx-合并数据

时间:2018-10-05 11:22:54

标签: angular redux ngrx ngrx-store

我只是学习 ngrx ,不了解如何更改模型/合并,仅是简单的更改。 我在ngOnInit中得到了数据:

  

this.store.dispatch(new GetHeroes());

     

this.heroes $ = this.store.select(fromSelectors.getParticipants);

     

this.store.dispatch(new GetClients());

     

this.clients $ = this.store.select(fromSelectors.getClients);

在显示HTML中的 heroes $数据之前,我需要 this.heroes $ .push({name:'newName'}) this.heroes $ .push(this.clients $ [0]) 但是我的模型如下:存储:{actionsObserver:{....}}

我很困惑,请帮忙按照REDUX规则进行操作

只有一些存储文件:

//hero.actions.ts
...
export enum HeroActionTypes {
  heroGetHeroes = '[Hero] get',
  heroGetHeroesSuccess = '[Hero] get heroes success',
  .....
}


export class GetHeroes implements Action {
  readonly type = HeroActionTypes.heroGetHeroes;
}
export class GetHeroesSuccess implements Action {
  readonly type = HeroActionTypes.heroGetHeroesSuccess;
  constructor(public payload: Hero[]) {}
}

//hero.effects.ts
...
  @Effect()
  loadHeroes$ = this.actions$.pipe(
    ofType(HeroActionTypes.heroGetHeroes),
    switchMap(() =>
      this.heroService
        .getHeroes()
        .pipe(
          map(heroes => new GetHeroesSuccess(heroes)),
          catchError(error => of(new HeroError(error)))
        )
    )
  );
// hero.reducer.ts
switch (action.type) {
    case HeroActionTypes.heroGetHeroes:
      return {
        ...state,
        loading: true
      };
    case HeroActionTypes.heroGetHeroesSuccess:
      return adapter.addAll(action.payload, {
        ...state,
        loading: false,
        loaded: true
      });
// hero.selectors.ts
export const getHeroes = createSelector(getHeroEntities, entities => {
  return Object.values(entities);
});

客户代码也几乎相同

1 个答案:

答案 0 :(得分:0)

  

我需要this.heroes $ .push({name:'newName'})和this.heroes $ .push(this.clients $ [0])

这就是所有错误所在。您不必这样做,也不应该这样做。 唯一可以更改状态的地方是减速器内部。

要解决您的问题,您必须像从前那样,从效果中派出成功动作,并将数据作为有效负载。从效果中分派的动作将通过减速器,您可以在其中返回新状态。我看到您正在使用@ngrx/entity,这意味着addAll函数会将新实体添加到您的状态。

它到底在哪里出错,或者您需要对操作流程进行解释?因为您的代码段有效。