【问题标题】:NGXS typed raw state valueNGXS 类型的原始状态值
【发布时间】:2023-02-23 19:01:38
【问题描述】:

我无法在 NGXS 文档中找到有关如何键入状态对象的示例。

我想键入 Store 的快照方法的返回值。

例如

this.store.snapshot().SOME_STATE_SLICE

有没有办法做到这一点?

【问题讨论】:

    标签: angular typescript ngxs


    【解决方案1】:

    您可以定义要为其拍摄快照的切片,然后将其键入,例如,如果您具有以下状态:

    interface UserStateModel {
      readonly name: string;
    }
    
    export const USER_STATE_TOKEN = new StateToken<UserStateModel>('user');
    
    @State<UserStateModel>({
      name: USER_STATE_TOKEN,
    })
    export class UserState {
      @Selector()
      static name(state: UserStateModel) {
        return state.name;
      }
    }
    

    然后你可以在你的组件中做:

    const name = this.store.selectSnapshot(UserState.name);
    

    【讨论】:

    • 谢谢。这很酷。我也可以做 const user = this.store.selectSnapshot(UserState); 这将从状态返回用户对象。但是,是否可以键入 .snapshot() 的返回类型?
    • 为了选择整个用户状态对象,我编辑了我的答案,将状态标记分离为一个常量并将其导出,因为您不能在 selectSnapshot 中使用 UserState,而是需要使用状态标记,例如:const user = this .store.selectSnapshot(USER_STATE_TOKEN);
    猜你喜欢
    • 2019-02-01
    • 1970-01-01
    • 2019-08-02
    • 2018-10-11
    • 2018-08-03
    • 2018-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多