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

标签 angular typescript redux rxjs ngxs

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

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

例如,我得到了商店中展示的以下型号。本例中的问题是,从 DeviceState 获取 selectedDevicedeviceId 并在 中使用它的最佳方法是什么? DeviceHistoryState 返回所选设备的所有项目历史记录。

当然,我可以将 DeviceHistory 集成到设备模型中,但这并不能解决在多个状态之间执行操作的问题。我也不想将 selectedDevice 复制到 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
    }
}

最佳答案

最简单的选择是使用 Joining Selector .

@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 版本,因为选择器的注入(inject)参数选项最近(以及即将发生的更改)。

您还可以使用动态选择器来完成此操作,传入设备 ID 并获取该设备的过滤历史记录:

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

关于angular - 如何在不重复存储对象的情况下在多个状态模型之间进行交互 - NGXS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60577057/

相关文章:

angular - Observable.zip 不是函数

reactjs - TypeScript + VSCode 中的自定义模块分辨率

typescript - Redux 操作类型的字符串与常量

angular - 'formDirective' 被定义为类 'ControlContainer' 中的访问器,但在 'ConnectArrayDirective' 中作为实例属性被覆盖

javascript - Angular:无效的配置对象。 Webpack 已使用与 API 架构不匹配的配置对象进行初始化

Angular 5 common.js : 263 Uncaught ReferenceError: $ st is not defined

jquery - 在带有 jQ​​uery 的 TypeScript 中,为什么我会收到错误 'this' 隐式具有类型 any

reactjs - 如何修改reducer中已有的数据?

angular - 在子模块中使用导入模块中的组件

angular - QueryList 更改订阅不起作用