我正在使用ngrx Effects来对服务器进行http调用。但是效果并没有被调用。我想在组件加载时进行http调用。因此,我在ngOnInit中执行了一次store.dispatch,但是什么也没发生。
users.component.ts:
import { Component, OnInit } from '@angular/core';
import { Store } from '@ngrx/store';
import * as fromUsersReducer from './states/users.reducer';
import * as UsersActions from './states/users.action';
export class UsersComponent implements OnInit {
constructor(
private store: Store<fromUsersReducer.State>,
) { }
ngOnInit() {
this.store.dispatch(new UsersActions.Load());
}
}
users.actions.ts
export enum UsersActionTypes {
Load = '[Users] Load',
LoadSuccess = '[Users] Load Success',
LoadFail = '[Users] Load Fail',
}
export class Load implements Action {
readonly type = UsersActionTypes.Load;
}
export class LoadSuccess implements Action {
readonly type = UsersActionTypes.LoadSuccess;
constructor(public payload: Users[]) {}
}
export class LoadFail implements Action {
readonly type = UsersActionTypes.LoadFail;
constructor(public payload: string) {}
}
export type UsersActions = Load | LoadSuccess | LoadFail;
users.effects.ts
@Injectable()
export class UsersEffects {
constructor(private action$: Actions, private usersService: UsersService) {}
@Effect()
loadUsersDetails$ = this.action$.pipe(
ofType(UsersAction.UsersActionTypes.Load),
mergeMap((action: UsersAction.Load) =>
this.usersService.getUsers().pipe(
map(response => {
if (response) {
let users = new Array<Users>();
console.log(response);
.........
return new UsersAction.LoadSuccess(users);
}
}),
catchError(err => of(new UsersAction.LoadFail(err)))
)
)
);
}
users.reducer.ts
export interface State extends fromRoot.State {
users: UsersState;
}
export interface UsersState {
users: Users[];
}
const getUsersFeatureState = createFeatureSelector<UsersState>('users');
export const getUsersDetails = createSelector(
getUsersFeatureState,
state => state.users
);
export const initialState: UsersState = {
users: [],
};
export function reducer(state = initialState, action: UsersActions) {
switch (action.type) {
case UsersActionTypes.LoadSuccess:
console.log('Users Reducer - Received Full Data for Users: ', action.payload);
return {
...state,
users: action.payload,
};
default:
return state;
}
}
users.module.ts
@NgModule({
declarations: [UsersComponent],
imports: [
CommonModule,
SharedModule,
MaterialModule,
StoreModule.forFeature('users', reducer),
EffectsModule.forRoot([UsersEffects])
],
exports: [UsersComponent],
providers: [UsersService],
entryComponents: [UsersComponent]
})
export class UsersModule { }
app.module.ts
@NgModule({
declarations: [AppComponent],
imports: [
StoreModule.forRoot({}),
EffectsModule.forRoot([]),
],
............
})
export class AppModule {}
我可能会缺少什么?