什么是 Angular Ngrx Store 里的 Meta-Reducer

本文选择了 Angular 团队提供的官方 Heroes Angular 应用程序作为起始应用程序来展示 Angular 的特性。

为了展示 ngrx/store 模块在处理 Angular Feature 模块方面的强大功能,我不得不通过引入一个名为 Heroes 的新 Feature 模块来重构一些 Heroes 应用程序。该模块现在包含所有与 Hero 相关的代码和组件。您可以通过以下链接检查与 ngrx/store 模块集成的最终 Heroes 应用程序:https://stackblitz.com/edit/angular-tour-of-heroes-example。

重构后的工程如下图所示:

[图片]

  • @ngrx/store: @ngrx/store 包代表主要的 NgRX 存储包。
  • @ngrx/store-devtools:@ngrx/store-devtools 包有助于检测 Store,让您可以使用著名的 Redux DevTools Chrome 扩展来调试应用程序
  • @ngrx/effect:@ngrx/effects 包处理在应用程序中使用 ngrx/store 模块的 effect,即向远端服务器发起的数据读写请求
  • @ngrx/router-store:@ngrx/router-store 包将 Angular 路由器与 ngrx/store 模块集成在一起。 Store 代表一个应用程序的 single source of truth,因此,在这个 Node 包的帮助下,Store 可以访问与路由器相关的信息

将上述开发包导入 Angular 应用:


import {
    
     StoreModule, MetaReducer } from '@ngrx/store';
import {
    
     EffectsModule } from '@ngrx/effects';
import {
    
     StoreDevtoolsModule } from '@ngrx/store-devtools';
import {
    
     storeFreeze} from 'ngrx-store-freeze';

import {
    
    
    StoreRouterConnectingModule,
    RouterStateSerializer
} from '@ngrx/router-store';

import {
    
    
    AppState,
    reducers,
    CustomSerializer,
    effects
} from './store';

export const metaReducers: MetaReducer<any>[] = !environment.production ? [storeFreeze] : [];

export const storeDevTools: ModuleWithProviders[] = 
    !environment.production ? [StoreDevtoolsModule.instrument()] : [];

@NgModule({
    
    
    imports: [
        ...
        StoreModule.forRoot((reducers) as any, {
    
     metaReducers }), EffectsModule.forRoot(effects),
            storeDevTools,
            ...
    ],
    ...

MetaReducer 类型表示更高阶的 reducer。 reducer 充当纯函数,因此 MetaReducer 代表更高阶的函数。 根据定义,高阶函数表示接受的输入参数类型是函数,返回的值是另一个函数的函数。

MetaReducer 类型接受一个 reducer 作为输入参数,并返回一个与 reducer 签名完全相同的函数。 ngrx/store 模块在内部组合了所有提供的减速器,并用提供的 meta 减速器包装它们。 ngrx/store 模块保证 meta-reducer 函数在实际 reducer 之前首先运行。

猜你喜欢

转载自blog.csdn.net/i042416/article/details/125951848