我对照该项目angular5 的版本改写;我需要用到一个数组(address),循环遍历它时报错:Cannot read property ‘ids’ of undefined,我用了ngrx/entity;
运行的到的address 状态:
addressList(pin):{
ids(pin):[‘1’,‘2’,‘3’],
entities(pin):{
1(pin): {id:1 ,desc: ‘A楼’}
2(pin): {id:2 ,desc: ‘B楼’}
3(pin): {id:3 ,desc: ‘C楼’}
}
slectedId(pin): null
}
部分代码如下:
action :
export class LoadingAddressSuccessAction implements Action {
readonly type = LOAD_ADDRESS_SUCCESS;
constructor(public payload: AddressTree[]) { }
}
reducer:
export interface State extends EntityState {
selectedId: string | null;
}
export const adapter: EntityAdapter = createEntityAdapter({
sortComparer: false
});
export const initialState: State = adapter.getInitialState({
selectedId: null
});
export function reducer(state = initialState, action: actions.Actions): State {
switch (action.type) {
case actions.LOAD_ADDRESS_SUCCESS: {
return {
…adapter.addMany(action.payload, state),selectedId: null
}
}
case actions.LOAD_ADDRESS_FAIL:
default: {
return state;
}
}
}
export const getSelectedId=(state: State)=> state.selectedId;
reducer的index文件:
export const getAddressState = createFeatureSelector<fromAddress.State>(‘addressTree’);
export const {
selectIds: getAddressIds,
selectEntities: getAddressEntities,
selectAll: getAddress,
selectTotal: getAddressTotal
} = fromAddress.adapter.getSelectors(getAddressState);
全网首个介绍官方 Material 组件库用法与 Redux 在 Angular 中的应用
了解课程