我有角度4.4.3项目,ngrx 4.0.3和angular-cli 1.1.2。
当我没有使用 aot 选项时一切正常,但是当我使用--aot = true时,我可以看到没有调用减速器(因为我看不到控制台输出' REDUCER FIRED'):
动作:
import { Post } from '../models';
import {Action as NgRxAction} from '@ngrx/store';
export interface Action extends NgRxAction {
payload?: any;
}
@Injectable()
export class PostActions {
static LOAD_POSTS = '[Post] Load Posts';
loadPosts(): Action {
return {
type: PostActions.LOAD_POSTS
};
}
...
...
}
效果:
import { AppState } from '../reducers';
import { PostActions, Action } from '../actions';
import { LoadHtmlServiceService } from '../services/load-html-service.service';
import 'rxjs/add/operator/switchMap';
@Injectable()
export class PostEffects {
constructor(
private update$: Actions,
private postActions: PostActions,
private svc: LoadHtmlServiceService
) { }
@Effect() loadPosts$ = this.update$
.ofType(PostActions.LOAD_POSTS)
.switchMap(() => this.svc.getAllSections())
.map(posts => this.postActions.loadPostsSuccess(posts));
...
...
}
减速器/后列表:
import { PostActions, Action } from '../actions';
export type PostListState = Post[];
const initialState: PostListState = [];
export default function (state = initialState, action: Action): PostListState {
console.log('REDUCER FIRED!!!!')
switch (action.type) {
case PostActions.LOAD_POST_SUCCESS: {
return action.payload;
}
...
...
}
}
减速器/索引:
import postListReducer, * as fromPostList from './post-list';
import postReducer, * as fromPost from './post';
import userReducer, * as fromUser from './user';
export interface AppState {
posts: fromPostList.PostListState;
post: fromPost.PostState;
user: fromUser.UserState;
};
export const reducers: ActionReducerMap<AppState> = {
posts: postListReducer,
post: postReducer,
user: userReducer
};
app.module:
import { reducers } from './reducers';
import { PostEffects } from './effects';
@NgModule({
declarations: [
AppComponent
],
entryComponents: [AddSectionModalComponent],
imports: [
LayoutModule
StoreModule.forRoot(reducers),
EffectsModule.forRoot([PostEffects])
]
...
...
我忘了什么地方?
非常感谢ngrx peolpe
答案 0 :(得分:2)
终于想出了如何使我的代码运行--aot:
诀窍是:
在 reducers / index 上定义injectionToken:
export const reducerToken = new InjectionToken<ActionReducerMap<AppState>>('Registered Reducers');
Object.assign(reducerToken, reducers);
定义getReducers工厂( app.module ):
export function getReducers() {
return reducers;
}
在 app.module 上注册模块时: 注册reducerToken并在提供者部分提供:
imports:[
...
...
StoreModule.forRoot(reducerToken),
EffectsModule.forRoot([PostEffects])
],
providers: [
{
provide: reducerToken,
useFactory: getReducers
}