I am currently utilizing ngrx Effects to send a http call to my server, but for some reason the effect is not triggered. My goal is to initiate the http call when the component loads. I have tried using store.dispatch in ngOnInit, however, nothing seems to happen.
In 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());
}
}
In 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;
In 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)))
)
)
);
}
In 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;
}
}
In 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 { }
In app.module.ts:
@NgModule({
declarations: [AppComponent],
imports: [
StoreModule.forRoot({}),
EffectsModule.forRoot([]),
],
............
})
export class AppModule {}
Any suggestions on what might be causing the issue?