使用普通的@ngrx,如果我需要为某事实现多个状态,我会这样做:
export interface FeatureStates{
[featureStateId: string]: FeatureState;
}
export interface FeatureState{
propertyOne: string;
propertyTwo: Items[];
}
const initialStates: FeatureStates = {};
const initialState: FeatureState= {
propertyOne: "",
propertyTwo: []
};
const createStateIfNeeded = (states: FeatureStates, id: string, propertyOne: string): FeatureStates => {
if(!states[id]){
return {
...states,
[id]: {
...initialState,
propertyOne: propertyOne
}
};
}
return states;
};
const _featureReducers = createReducer(
initialStates,
on(FeatureActions.actionName, (states, action)=>{
const id = action.id;
const propertyOne = action.propertyOne;
const newState = createStateIfNeeded(states, id, propertyOne);
return newState;
})
);
export const featureReducers = (states: FeatureStates, action: Action)=>_featureReducers (states, action);
该用例用于实现使用自动完成的“项目选择器”的自定义小部件。有一种情况,小部件需要在同一部分中使用两次,并且两个小部件都需要具有单独的状态。我将如何使用@ngrx/data实现这一目标?
到目前为止,我唯一的解决方案需要手动操作。
首先,我在 EntityMetadataMap 中添加了一个不同的实体元数据,它只有一个不同的名称......
const entityMetadata: EntityMetadataMap = {
Users: {
entityName: "Items",
additionalCollectionState: {
hasMore: false
},
selectId: (entity: Item)=>entity.Id!
},
PickerUsers: {
entityName: "ItemsPicker",
entityDispatcherOptions: {
optimisticAdd: false,
optimisticUpdate: true
},
selectId: (entity: Item)=>entity.Id!
}
}
然后,我为它创建一个服务......
@Injectable({
providedIn: "root"
})
export class ItemPickerService extends EntityCollectionServiceBase<Item>{
constructor(serviceElementsFactory: EntityCollectionServiceElementsFactory){
super("ItemsPicker", serviceElementsFactory)
}
}
此解决方案不适合生产,如果我需要使用小部件 3 或 4 次,我必须继续这样做。必须有一种方法可以以编程方式执行此操作,或者根据我迄今为止所做的研究,这是不可能的。