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.但我也无法访问该存储!。此外,我确定这不是访问一项服务...
SomeClass.getServiceInstance(type)?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方法的实现有问题。
如果您在我的代码中看到任何错误,请告诉我。
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 没有正确传递或初始化。我想我还是做错了什么
您应该尝试使用记录的META_REDUCERS令牌注入元减速器:
(注意:截至 9 月 24 日,文档有点误导,工厂方法返回类型应该是,MetaReducer而不是。在代码库中MetaReducer[]检查此示例)
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 {}\nRun Code Online (Sandbox Code Playgroud)\n\n更新:
\n\n从 v8 开始,您可以使用\xc3\x99SER_PROVIDED_META_REDUCERS令牌:
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],\nRun Code Online (Sandbox Code Playgroud)\n\n在这种情况下,提供的工厂方法必须返回MetaReducer[]。在此函数中,“库”和“用户”提供的元缩减器都合并为一个集合。
您很可能会遇到存储和记录器服务之间的循环依赖关系,因为在创建存储期间,Angular\xc2\xb4s IOC 容器将在创建存储之前尝试实例化依赖于存储的记录器服务已最终确定。您可以通过“惰性”访问记录器服务中的存储来解决此问题,方法是将 Injector 注入其中并为存储定义 getter 属性,如下所示:
\n\nprivate get() store{return this.injector.get(Store);}\n\nctor(private readonly injector: Injector){}\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
3279 次 |
| 最近记录: |