gpt4 book ai didi

angular - 在 NgRx 中强类型化存储的目的是什么?

转载 作者:行者123 更新时间:2023-12-04 01:32:45 25 4
gpt4 key购买 nike

CoreModule 是一个预先加载的模块,包含应用程序启动时所需的状态。

import * as fromCore from './state/core.reducer';

@NgModule({
...
imports: [
StoreModule.forRoot({ core: fromCore.reducer }),

DocumentModule 是一个延迟加载的模块。
import * as fromDocument from './state/document.reducer';

@NgModule({
...
imports: [
StoreModule.forFeature('document', fromDocument.reducer),

DocumentComponent 注入(inject)存储。
import * as fromDocument from './state/document.reducer';

constructor(private store: Store<fromDocument.State>) { }

fromDocument.State 扩展了“核心”状态。
import * as fromCore from '../../core/state/core.reducer';

export interface State extends fromCore.State {
document: DocumentState;
}

这是一种我看到到处都在使用的方法,但我认为它没有任何好处。当我将它设置为 fromDocument.State 不扩展 fromCore.State 时,我仍然可以访问 DocumentComponent 中状态树的“核心”部分。
this.user$ = this.store.select(fromCore.getUser);

通过将存储注入(inject)组件中,我始终可以访问完整的状态树,无论我如何键入存储。那么强类型存储的目的究竟是什么?为什么不到处使用 Store 呢?我与 store 对象交互的唯一方法是 store.select 和 store.dispatch 所以就我所见没有打字好处?

最佳答案

具体点
在您提到的特定情况下,键入将有助于 select 的过载。将映射函数作为参数,例如this.store.select(s => ....) .
不过,NgRx 仍然允许您进行无类型选择。 GitHub上的相关讨论:https://github.com/ngrx/store/issues/60
一般来说
来自 TypeScript 和其他花哨的东西的强类型(公平地说,所有编程语言的大多数特性)不是为了

  • 自动验证您的程序
  • 充当某种安全功能(防止数据泄露)

  • 相反,它们是我们可怜的人类开发人员的拐杖,以避免犯我们通常在自己的代码中编写的愚蠢错误。
    示例:例如尝试调用 user.namme而不是 user.name在代码的一个模糊的、被遗忘的部分中,这将导致一连串的错误。想象一下,它只向用户显示一些“未定义”和“登录错误”,在一个陌生的地方,并且只有当他按照一定的顺序执行 5 个非常具体的操作时,有点难以追溯和重现。
    如果您使用强类型,编译器会在投入生产之前快速检测到这一点。

    关于angular - 在 NgRx 中强类型化存储的目的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60575758/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com