关于前端:什么是-Angular-Ngrx-Store-里的-MetaReducer

4次阅读

共计 1505 个字符,预计需要花费 4 分钟才能阅读完成。

本文抉择了 Angular 团队提供的官网 Heroes Angular 应用程序作为起始应用程序来展现 Angular 的个性。

为了展现 ngrx/store 模块在解决 Angular Feature 模块方面的弱小性能,我不得不通过引入一个名为 Heroes 的新 Feature 模块来重构一些 Heroes 应用程序。该模块当初蕴含所有与 Hero 相干的代码和组件。您能够通过以下链接查看与 ngrx/store 模块集成的最终 Heroes 应用程序:https://stackblitz.com/edit/a…。

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

  • @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 之前首先运行。

正文完
 0