ngrx:选择器类型映射

时间:2017-03-14 08:37:10

标签: angular typescript ngrx

这是我的IStore

export interface IStore {
  plans: IPlanRedux;
}

其中IPlanRedux是:

export interface IPlanRedux {
    entities: { [key: string]: IPlan };
    ids: Array<string>;
}

export interface IPlan {
    id?: string;
    name?: string;
}

所以,我需要从plan状态创建选择器。我创建的选择器是:

plan.selectors.ts

export const getEntities = (planRdx: IPlanRedux) => planRdx.entities;
export const getIds = (planRdx: IPlanRedux) => planRdx.ids;

export const getAll = createSelector(getEntities, getIds, (entities, ids) => { return ids.map(id => entities[id]); });

root.selectors.ts

export const getPlansState = (state: IStore) => state.plans;
export const getPlanEntities = createSelector(getPlansState, fromPlans.getAll);

我遇到了编译器错误,我不知道如何解决。我正在尝试使用getPlanEntities选择器创建订阅到我的组件中以获取所有实体:

this.store$.select(fromRoot.getPlanEntities)
    .map(plan => {
        if (plan.id != null)
        {
            return {id: plan.id, text: plan.name};
        }
    });

问题在于参数类型plan。编译器告诉我,plan的类型是IPlan[],而不是IPlan。所以,我收到了Property 'id' does not exist on type 'IPlan[]'之类的编译器错误,因为planIPlan[]而不是IPlan

我不知道如何处理这个问题。无论如何都要逐个获取单个实体而不是单个数组?

修改

我想要实现的目标是从Observable<IPlan>向我的组件中this.store$.select(fromRoot.getPlanEntities)

private plans$: Observable<IPlan>;
constructor(private store$: Store<IStore>, private fb: FormBuilder, private router: Router, injector: Injector)
{
    this.plans$ = this.store$.select(fromRoot.getPlanEntities)
        .map(planEntities => {
            return planEntities
                .find(plan => plan.id != null)
                .map(plan => ({id :plan.id, text: plan.name}));
        });
 ...

并在模板上使用它以列出所有当前计划:

<div class="clearfix">
    <div *ngIf="plans$ | async">
        <div [innerHTML]="(plans$ | async).name"></div>
   </div>

1 个答案:

答案 0 :(得分:1)

我认为你在这里误解了map

this.store$.select(fromRoot.getPlanEntities)
  .map(plan => {
      if (plan.id != null)
      {
          return {id: plan.id, text: plan.name};
      }
  });

map上不是ES6 map而是Observable。 您只需检索planEntities 如果你想获得一个实体,你应该这样做:

this.store$.select(fromRoot.getPlanEntities)
  .map(planEntities => {
    return planEntities
      .find(plan => plan.id !== null)
      .map(plan => ({ id: plan.id, text: plan.name }));
  })
  .do((plan: {id: any, text: string}) => /* DO WHATEVER YOU WANT HERE */);