NgRx:如何在元减速器中使用服务?

Dav*_*rez 6 dependency-injection ionic-framework ngrx angular ionic4

我使用自定义中间件 ( meta-reducer ) 打印我的ngrx-store每次操作被分配。我直接在里面写了我的中间件app.module.ts(我应该把它放在哪里?):

app.module.ts

// ...imports

// ...

// FIXME:
/**
 * console.log action and state(before action) each time an action is dipatched
 * @param reducer reducer
 */
export function debug(reducer: ActionReducer<AppState, Actions>): ActionReducer<AppState, Actions> {

    const logger = new LoggerService(); ////////////// ERROR \\\\\\\\\\\\\\

    return (state, action) => {

        logger.storeInfo('ACTION', action);
        logger.storeInfo('STATE', state);

        return reducer(state, action);
    };
}

export const metaReducers: MetaReducer<any>[] = [
    debug,
];

@NgModule({
    declarations: [AppComponent, LoggerServiceComponent],
    entryComponents: [],
    imports: [
        // ...
        StoreModule.forRoot(reducers, { metaReducers }),
        StoreRouterConnectingModule.forRoot(), // Connects RouterModule with StoreModule
    ],
    providers: [
       // ...
    ],
    bootstrap: [AppComponent],
})
export class AppModule {}
Run Code Online (Sandbox Code Playgroud)

有一个错误,因为我LoggerService注入了一个存储(因为我希望我的所有日​​志都存储在ngx-store.但我也无法访问该存储!。此外,我确定这不是访问一项服务...

  • 我应该将我的 meta reducer 放在一个类中,然后访问该类的函数,但我该怎么做?
  • 是否有访问任何服务的通用方法,例如SomeClass.getServiceInstance(type)
  • 你对如何做到这一点有其他想法吗?

[编辑 1] - 使用META_REDUCERS(第一次尝试 - 失败)

app.module.ts

import { LoggerService } from './services/logger.service';
import { AppState, Actions } from './app.state';
import { StoreModule, MetaReducer, ActionReducer, META_REDUCERS } from '@ngrx/store';

/**
 * Injects a `LoggerService` inside a `MetaReducer`
 * @param logger a service that allows to log and store console.log() messages
 * @returns a `MetaReducer`
 */
function debugFactory(logger: LoggerService): MetaReducer<AppState> {
    return (reducer: ActionReducer<AppState, Actions>): ActionReducer<AppState, Actions> => {
        return (state, action) => {

           logger.storeInfo('ACTION', action);
           logger.storeInfo('STATE', state);

           return reducer(state, action);
        };
    };
}

/**
 * Injects a LoggerService inside the debug `MetaReducer` function
 * @param logger a service that allows to log and store console.log() messages
 * @returns A list of `MetaReducer`
 */
export function getMetaReducers(logger: LoggerService): MetaReducer<AppState>[] {
    return [debugFactory(logger)];
}

const reducers = {
    layout: layoutReducer,
    preferences: preferencesReducer,
    router: routerReducer,
    debug: debugReducer,
};

@NgModule({
    declarations: [AppComponent ],
    entryComponents: [],
    imports: [
        // ...
        StoreModule.forRoot(reducers),
        StoreRouterConnectingModule.forRoot(), // Connects RouterModule with StoreModule
    ],
    providers: [
        // ...
        {
            provide: META_REDUCERS,
            deps: [LoggerService],
            useFactory: getMetaReducers,
            multi: true,
        },
    ],
    bootstrap: [AppComponent],
})
export class AppModule {}
Run Code Online (Sandbox Code Playgroud)

根据文档,这应该可以工作,但在运行时出现以下错误:

TypeError: "fn is not a function"
Run Code Online (Sandbox Code Playgroud)

对应这个函数(在njrx-store库中):

TypeError: "fn is not a function"
Run Code Online (Sandbox Code Playgroud)

在调试器中,它显示函数数组( ...functions) 包含一些函数和一个数组,我怀疑这是方法的结果getMetaReducers。我怀疑这个例子是错误的,或者compose方法的实现有问题。

如果您在我的代码中看到任何错误,请告诉我。

[编辑 2] - 使用USER_PROVIDED_META_REDUCERS答案中提到的(第二次尝试 - 失败)

已编辑的代码

/**
 * @param {...?} functions
 * @return {?}
 */
function compose(...functions) {
    return (/**
     * @param {?} arg
     * @return {?}
     */
    function (arg) {
        if (functions.length === 0) {
            return arg;
        }
        /** @type {?} */
        const last = functions[functions.length - 1];
        /** @type {?} */
        const rest = functions.slice(0, -1);
        return rest.reduceRight((/**
         * @param {?} composed
         * @param {?} fn
         * @return {?}
         */
        (composed, fn) => {
             return fn(composed) // <----- HERE
        }), last(arg));
    });
}
Run Code Online (Sandbox Code Playgroud)

似乎我LoggerService的既没有正确通过也没有初始化,因为我现在有这个错误:

core.js:9110 ERROR TypeError: Cannot read property 'storeInfo' of undefined
    at http://localhost:8102/main.js:636:20
    at http://localhost:8102/vendor.js:109798:20
    at computeNextEntry (http://localhost:8102/vendor.js:108628:21)
    at recomputeStates (http://localhost:8102/vendor.js:108681:15)
    at http://localhost:8102/vendor.js:109029:26
    at ScanSubscriber.StoreDevtools.liftedAction$.pipe.Object.state [as accumulator] (http://localhost:8102/vendor.js:109081:38)
    at ScanSubscriber._tryNext (http://localhost:8102/vendor.js:120261:27)
    at ScanSubscriber._next (http://localhost:8102/vendor.js:120254:25)
    at ScanSubscriber.next (http://localhost:8102/vendor.js:114391:18)
    at WithLatestFromSubscriber._next (http://localhost:8102/vendor.js:122330:34)
Run Code Online (Sandbox Code Playgroud)

如果我评论这些行:

// OLD

    providers: [
        // ...
        {
            provide: META_REDUCERS,
            deps: [LoggerService],
            useFactory: getMetaReducers,
            multi: true,
        },
    ],

// NEW

    providers: [
        // ...
        {
            provide: USER_PROVIDED_META_REDUCERS,
            deps: [LoggerService],
            useFactory: getMetaReducers,
        },
    ],
Run Code Online (Sandbox Code Playgroud)

不会抛出任何异常,但我的记录器也不会工作。

但至少 store 自己配置正确,现在的问题只是 LoggerService 没有正确传递或初始化。我想我还是做错了什么

Jot*_*edo 6

您应该尝试使用记录的META_REDUCERS令牌注入元减速器:

\n\n

注意:截至 9 月 24 日,文档有点误导,工厂方法返回类型应该是,MetaReducer而不是。在代码库中MetaReducer[]检查此示例)

\n\n
export debugFactory(logger: LoggerService): MetaReducer<AppState> {\n return (reducer: ActionReducer<AppState, Actions>): ActionReducer<AppState, Actions> => {\n    return (state, action) => {\n\n        logger.storeInfo(\'ACTION\', action);\n        logger.storeInfo(\'STATE\', state);\n\n        return reducer(state, action);\n    };\n  }\n}\n\n@NgModule({\n  providers: [\n    {\n      provide: META_REDUCERS,\n      deps: [LoggerService],\n      useFactory: debugFactory,\n      multi: true\n    },\n  ],\n})\nexport class AppModule {}\n
Run Code Online (Sandbox Code Playgroud)\n\n

更新:

\n\n

从 v8 开始,您可以使用\xc3\x99SER_PROVIDED_META_REDUCERS令牌:

\n\n
export function getMetaReducers(logger: LoggerService): MetaReducer<AppState>[] {\n return [debugFactory(logger)];\n}\n\nproviders: [\n  {\n     provide: USER_PROVIDED_META_REDUCERS,\n     deps: [LoggerService],\n     useFactory: getMetaReducers\n  },\n],\n
Run Code Online (Sandbox Code Playgroud)\n\n

在这种情况下,提供的工厂方法必须返回MetaReducer[]在此函数中,“库”和“用户”提供的元缩减器都合并为一个集合。

\n\n

您很可能会遇到存储和记录器服务之间的循环依赖关系,因为在创建存储期间,Angular\xc2\xb4s IOC 容器将在创建存储之前尝试实例化依赖于存储的记录器服务已最终确定。您可以通过“惰性”访问记录器服务中的存储来解决此问题,方法是将 Injector 注入其中并为存储定义 getter 属性,如下所示:

\n\n
private get() store{return this.injector.get(Store);}\n\nctor(private readonly injector: Injector){}\n
Run Code Online (Sandbox Code Playgroud)\n

  • 小心!如果您想在功能级别进行metareducer依赖注入并且找不到如何操作,它隐藏在文档中[此处](https://ngrx.io/guide/store/recipes/injecting#injecting-feature-config) (2认同)