在 NgRx 中强类型存储的目的是什么?
What is the purpose of strongly typing the store in NgRx?
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 注入商店。
import * as fromDocument from './state/document.reducer';
constructor(private store: Store<fromDocument.State>) { }
fromDocument.State 扩展 'core' 状态。
import * as fromCore from '../../core/state/core.reducer';
export interface State extends fromCore.State {
document: DocumentState;
}
我看到这种方法无处不在,但我看不到它有任何好处。当我将其设置为 fromDocument.State 不扩展 fromCore.State 时,我仍然可以访问 DocumentComponent.
中状态树的 'core' 部分
this.user$ = this.store.select(fromCore.getUser);
通过在组件中注入商店,我始终可以访问完整的状态树,无论我如何输入商店。那么强类型商店的目的究竟是什么?为什么不到处使用 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 个非常具体的操作时,才有点难以追溯和重现。
如果您使用强类型,编译器会在投入生产之前快速检测到这一点。
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 注入商店。
import * as fromDocument from './state/document.reducer';
constructor(private store: Store<fromDocument.State>) { }
fromDocument.State 扩展 'core' 状态。
import * as fromCore from '../../core/state/core.reducer';
export interface State extends fromCore.State {
document: DocumentState;
}
我看到这种方法无处不在,但我看不到它有任何好处。当我将其设置为 fromDocument.State 不扩展 fromCore.State 时,我仍然可以访问 DocumentComponent.
中状态树的 'core' 部分this.user$ = this.store.select(fromCore.getUser);
通过在组件中注入商店,我始终可以访问完整的状态树,无论我如何输入商店。那么强类型商店的目的究竟是什么?为什么不到处使用 Store
具体点
在您提到的特定情况下,键入将有助于 select
的重载,该重载将映射函数作为参数,例如this.store.select(s => ....)
.
不过,NgRx 仍然允许您进行非类型选择。关于 GitHub 的相关讨论:https://github.com/ngrx/store/issues/60
一般
来自 TypeScript 的强类型和其他奇特的东西(公平地说,所有编程语言的大多数特性)并不意味着
- 为您的程序自动验证
- 充当某种安全功能(防止数据泄露)
它们的意思是 我们可怜的人类开发人员 的拐杖,以避免我们通常在自己的代码中犯下愚蠢的错误。
示例:比如尝试在代码的一个模糊、被遗忘的部分调用 user.namme
而不是 user.name
,这将导致一连串的错误。想象一下它只向用户显示一些“未定义”和“登录错误”,在一个陌生的地方,并且只有当他按特定顺序执行 5 个非常具体的操作时,才有点难以追溯和重现。
如果您使用强类型,编译器会在投入生产之前快速检测到这一点。