js/modules/ngrx-store/src/ngrx-store.module.ts
crusader 600957820f ing
2018-03-18 00:07:24 +09:00

115 lines
2.5 KiB
TypeScript

import {
NgModule,
Inject,
Optional,
ModuleWithProviders,
OnDestroy,
InjectionToken,
Injector,
} from '@angular/core';
import { Store, StoreModule, ReducerManager, combineReducers } from '@ngrx/store';
import {
_STORE,
_STORE_FEATURE,
createReducer,
} from './core';
import { NgRxStoreSelect } from './service';
@NgModule({})
export class NgRxStoreRootModule {
constructor(
@Optional() @Inject(_STORE) reducers: any,
reducerFactory: ReducerManager,
store: Store<any>,
parentInjector: Injector,
select: NgRxStoreSelect,
) {
select.connect(store);
if (reducers) {
for (const key in reducers) {
if (!reducers.hasOwnProperty(key)) {
continue;
}
const clazz = reducers[key];
const inst = parentInjector.get(clazz, new clazz());
reducerFactory.addReducer(key, createReducer(inst));
}
}
}
}
@NgModule({})
export class NgRStoreFeatureModule implements OnDestroy {
constructor(
@Optional() @Inject(_STORE_FEATURE) featureReducers: any,
reducerFactory: ReducerManager,
store: Store<any>,
parentInjector: Injector,
select: NgRxStoreSelect,
) {
select.connect(store);
if (featureReducers) {
if (typeof featureReducers.key !== 'string') {
featureReducers.reducers = featureReducers.key;
featureReducers.key = undefined;
}
const mapped: {[key: string]: any} = {};
for (const key in featureReducers.reducers) {
if (!featureReducers.reducers.hasOwnProperty(key)) {
continue;
}
const clazz = featureReducers.reducers[key];
const inst = parentInjector.get(clazz, new clazz());
mapped[key] = createReducer(inst);
}
if (featureReducers.key) {
reducerFactory.addFeature({
reducers: mapped,
reducerFactory: <any>combineReducers,
key: featureReducers.key
});
}
}
}
ngOnDestroy() {
}
}
@NgModule({
imports: [
StoreModule,
],
providers: [
NgRxStoreSelect
],
})
export class NgRxStoreModule {
static forRoot(reducers: any): ModuleWithProviders {
return {
ngModule: NgRxStoreRootModule,
providers: [
{ provide: _STORE, useValue: reducers },
],
};
}
static forFeature(featureName: string, reducers?: any): ModuleWithProviders {
return {
ngModule: NgRStoreFeatureModule,
providers: [
{ provide: _STORE_FEATURE, useValue: { featureName, reducers } },
],
};
}
}