当前位置: 首页 > Web前端 > JavaScript

AngularNgrxStore中的Meta-Reducer

时间:2023-03-27 11:34:59 JavaScript

是什么本文选择Angular团队提供的官方HeroesAngular应用作为入门应用来演示Angular的特性。为了展示ngrx/store模块在处理Angular功能模块方面的强大功能,我不得不通过引入一个名为Heroes的新功能模块来重构一些Heroes应用程序。该模块现在包含所有与Hero相关的代码和组件。您可以在以下链接查看与ngrx/store模块集成的最终Heroes应用程序:https://stackblitz.com/edit/a…。重构后的项目如下所示:@ngrx/store:@ngrx/store包代表主要的NgRX存储包。@ngrx/store-devtools:@ngrx/store-devtools包有助于检测Store,允许您使用著名的ReduxDevToolsChrome扩展调试您的应用程序@ngrx/effect:@ngrx/effects包处理应用程序中的使用ngrx/store模块的作用,即对远程服务器的数据读写请求@ngrx/router-store:@ngrx/router-store包集成了Angular路由器和ngrx/store模块。Store代表应用程序的单一真实来源,因此,借助于这个Node包,Store可以访问路由器相关信息将上述开发包导入Angular应用程序:import{StoreModule,MetaReducer}from'@ngrx/store';从'@ngrx/effects'导入{EffectsModule};从'@ngrx/store-devtools'导入{StoreDevtoolsModule};从'ngrx-store-freeze'导入{storeFreeze};从'@ngrx导入{StoreRouterConnectingModule,RouterStateSerializer}/router-store';import{AppState,reducers,CustomSerializer,effects}from'./store';exportconstmetaReducers:MetaReducer[]=!environment.production?[storeFreeze]:[];exportconststoreDevTools:ModuleWithProviders[]=!environment.production?[StoreDevtoolsModule.instrument()]:[];@NgModule({imports:[...StoreModule.forRoot((reducers)asany,{metaReducers}),EffectsModule.forRoot(effects),storeDevTools,...],...MetaReducer类型表示高阶reducer。reducer充当纯函数,因此MetaReducer表示高阶函数。根据定义,高阶函数意味着它接受一个函数的输入参数类型,并返回一个值是另一个函数的函数。MetaReducer类型将reducer作为输入参数,并返回一个与reducer具有完全相同签名的函数。ngrx/store模块在内部组合了所有提供的reducer,并用提供的metareducer包装它们。ngrx/store模块确保meta-reducer函数在实际的reducer之前首先运行。