如何在没有重复存储对象的情况下在多个状态模型之间进行交互-NGXS



为了降低应用程序中所有状态的复杂性,我决定使用NGXS,因为它使用的是TypeScript实现方式,非常适合Angular架构。但第一个问题出现得很快,因为与NGRX相比,NGXS没有添加额外的去耦减少层。

在多个状态模型之间进行交互的最佳实践是什么?假设您想要操作状态B,但此操作需要状态a的属性。我在文档中发现了可以处理此问题的共享状态概念,但这也是有限的,因为我不能在选择器中使用共享状态来根据状态a和B所需的操作为UI提供特定的选择。

例如,我得到了商店里展示的以下型号。这个例子中的问题是,从DeviceState中获得selectedDevicedeviceId以在DeviceHistoryState中使用它来返回所选设备的所有项目历史的最佳方式是什么。

当然,我可以将DeviceHistory集成到设备模型中,但这并不能解决在多个状态之间执行操作的问题。我也不想将selctedDevice复制到DeviceHistoryStateModel中。

export interface Device {
deviceId: string;
// More device details
}
export interface DeviceHistory {
deviceId: string;
itemHistoryMap: Map<number, ItemHistory[]>;
}
export class DeviceStateModel {
devices: Device[];
selectedDevice: Device;
}
@State<DeviceStateModel>({
name: 'devices',
defaults: {
devices: [],
selectedDevice: null
}
})
export class DeviceState {
}
export class DeviceHistoryStateModel {
devicesHistory: DeviceHistory[];
}
@State<DeviceHistoryStateModel>({
name: 'devicesHistory',
defaults: {
devicesHistory: []
}
})
export class DeviceHistoryState {
@Selector()
public static getHistory(state: DeviceHistoryStateModel) {
// ??? Best practise to return all the item histories of the selcted device 
}
@Action(GetItemHistory)
public getItemHistory() {
// Stores the item history for the device
}
}

最简单的选项是使用联接选择器。

@Selector()
public static getHistory(state: DeviceHistoryStateModel, deviceState: DeviceStateModel) {
// ??? Best practise to return all the item histories of the selcted device 
const selectedDevice = deviceState.selectedDevice;
//... get history items that match
}

第二个选项可能是您想要的,因为您希望在selectedDevice值更改时自动重新评估此历史选择器。

您可能还想检查您正在运行的NGXS的版本,因为选择器的注入参数选项最近(以及即将发生的更改(。

您还可以使用动态选择器沿着这些行进行操作,传入设备ID并返回该设备的过滤历史记录:

static getHistory(deviceId: string) {
return createSelector([DevicesHistoryState], (state: DevicesHistoryStateModel) => {
return state.devicesHistory.filter(h => h.deviceId === deviceId);
});
}

最新更新