Angular独立应用中如何为NGRX Store添加元Reducer?
Angular 15独立应用配置NGRX元Reducer解决方案
禁止混用
provideStore和StoreModule.forRoot
独立应用模式下,NGRX推荐使用provideStore作为新API,和传统的StoreModule.forRoot不能同时配置,否则会引发冲突,导致元Reducer无法执行。直接通过
provideStore配置元ReducerprovideStore的第二个参数支持传入StoreConfig对象,其中的metaReducers属性可直接接收元Reducer数组,示例代码如下:// main.ts import { bootstrapApplication } from '@angular/platform-browser'; import { provideStore } from '@ngrx/store'; import { AppComponent } from './app/app.component'; import { rootReducer } from './app/store/root.reducer'; import { loggerMetaReducer } from './app/store/meta-reducers/logger.meta-reducer'; bootstrapApplication(AppComponent, { providers: [ provideStore(rootReducer, { metaReducers: [loggerMetaReducer] // 在这里添加你的元Reducer }) ] });确认元Reducer写法合规
元Reducer必须符合NGRX的类型要求,以下是一个日志元Reducer的示例:// logger.meta-reducer.ts import { MetaReducer } from '@ngrx/store'; import { Action } from '@ngrx/store'; export function loggerMetaReducer(reducer: any): any { return (state: any, action: Action) => { console.log('上一状态:', state); console.log('触发动作:', action); const nextState = reducer(state, action); console.log('下一状态:', nextState); return nextState; }; }结合Feature States的场景
如果应用包含feature状态,使用provideState注册的同时,元Reducer依然通过provideStore的全局配置传入,会作用于所有reducer:import { provideStore, provideState } from '@ngrx/store'; import { counterReducer } from './app/store/counter/counter.reducer'; bootstrapApplication(AppComponent, { providers: [ provideStore(rootReducer, { metaReducers: [loggerMetaReducer] }), provideState({ name: 'counter', reducer: counterReducer }) ] });
为什么之前的方法无效?
你之前用importProvidersFrom(StoreModule.forRoot(...))的方式不生效,是因为独立应用中provideStore会覆盖StoreModule的配置,导致元Reducer没有被正确注册到全局store中。必须统一使用独立API的provideStore来配置全局store选项。
内容的提问来源于stack exchange,提问作者Marlau
相关产品推荐
相关产品推荐

