我目前正在 ngrx 项目中处理一个有点复杂(深层)的结构。它可以被认为是父对象的数组,具有多个级别的子对象。它在服务器端标准化/扁平化,我的商店中的功能看起来像这样:
rootObjs: {
level1: {
byId: {
'lvl1_1': {id: 'lvl1_1', label: '[Lvl 1]: 1', ui_open: true, children: ['lvl2_1', 'lvl2_3']},
'lvl1_2': {id: 'lvl1_2', label: '[Lvl 1]: 2', ui_open: false, children: ['lvl2_2']}
},
allIds: [
'lvl1_1', 'lvl1_2'
]
},
level2: {
byId: {
'lvl2_1': {id: 'lvl2_1', label: '[Lvl 2]: 1', ui_open: false, children: ['lvl3_1', 'lvl3_2']},
'lvl2_2': {id: 'lvl2_1', label: '[Lvl 2]: 2', ui_open: true, children: ['lvl3_3']},
'lvl2_3': {id: 'lvl2_1', label: '[Lvl 2]: 3', ui_open: false, children: []}
},
allIds: [
'lvl2_1', 'lvl2_2', 'lvl2_3'
]
},
level3: {
byId: {
'lvl3_1': {id: 'lvl3_1', label: '[Lvl 3]: 1', ui_open: false,},
'lvl3_2': {id: 'lvl3_2', label: '[Lvl 3]: 2', ui_open: false,},
'lvl3_3': {id: 'lvl3_3', label: '[Lvl 3]: 3', ui_open: false,},
}
allIds: [
'lvl3_1', 'lvl3_2', 'lvl3_3'
]
}
}
现在我正在尝试编写我的选择器。我的问题是所有对象都需要立即显示在屏幕上,但是它们都必须可以单独编辑。因此,我试图创建一个选择器,允许我单独选择每个组件 - 类似于:
export const rootObjFeature = createFeatureSelector<RootObj>('rootObjs');
export const selectLevel1 = (id: string) => createSelector(
rootObjFeature, (state: JobPlanner) => {
// Grab only the level2 children associated with selected level1
const lvl2 = state.level1.byId[id].children.map(key => state.level2.byId[key]);
// Grab only the level3 children of level2 associated with selected level1
const lvl3 = [].concat(
...state.lvl2.map( l2 => l2.children.map(key => state.level3.byId[key]));
);
return {
...state.level1.byId[id],
level2: lvl2,
level3: lvl3
};
}
);
然后在我的 Level1Component 初始化中,我做了这样的事情:
export class Level1Component implements OnInit, OnDestroy {
@Input() id: string;
lvl1Sub: Subscription;
lvl1: Level1Model;
constructor(private store: Store<AppState>) { }
ngOnInit() {
this.lvl1Sub = this.store.select(selectLevel1(this.id)).subscribe(l1 => {
console.log('loading level 1: '+this.id);
this.lvl1 = l1;
});
}
ngOnDestroy() {
this.lvl1Sub.unsubscribe();
}
}
通过这个设置我可以通过正确的level2
and level3
对象到它们自己的组件(可以打开、关闭、编辑这些子组件等)。然而,由于我有我的选择器,任何时候level1
, level2
, or level3
项目已编辑(例如-ui_open
被切换为lvl1_1
), 每一个level1
成分lvl1Sub
方法被调用。这是一个问题,因为我的视图可能有数百个 level1 组件,但一次只会编辑一个。有没有办法设置一个选择器,仅当与单个 ID 关联的那些存储元素发生更改时才会调用其订阅?