Let's say I have a few actions that my store can use: Load, LoadFail, and LoadSuccess. All my actions are very simple, LOAD = "load"
, LOAD_FAIL = "load failed"
, and LOAD_SUCCESS = "load success"
I have a simple reducer that switches on these, like so:
export function reducer(state: State = initialState, action: Actions): State {
switch (action.type) {
case Actions.LOAD: {
console.log("Actions.LOAD");
return state;
}
case Actions.LOAD_FAIL: {
console.log("Actions.LOAD_FAIL");
store.error = action.payload;
return state;
}
case Actions.LOAD_SUCCESS: {
console.log("Actions.LOAD_SUCCESS");
state.data = action.payload;
return state;
}
default: {
return state;
}
}
}
I have an effects class that handles the load dispatch:
@Injectable()
export class TestersEffects {
constructor(
private service: MyHttpService,
private actions$: Actions
) {}
@Effect() load$ = this.actions$.pipe(
ofType(Actions.LOAD),
switchMap(
action => {
return this.service.load().pipe(
map(data => {
console.log("load$ fired");
return new TestersActions.LoadSuccess(data);
}),
catchError(error => {
console.log("error");
return of (new Actions.LoadFail(error));
})
)
}
)
);
}
Finally, I'm using all of this as such:
export class MyClass implements OnInit {
data: any;
constructor(private store: Store<AppState>) {}
ngOnInit() {
this.store.dispatch(new Actions.Load());
this.store.select(store => store.State).subscribe(
data => this.data = data,
error => this.handleError(error)
);
}
handleError(error) {
//Whatever I'll do to handle this error
}
}
This code works fine when the server I'm requesting responds. However, I need to handle the situations in which it doesn't respond. I'm assuming that I simply don't understand the flow of ngrx/store well enough to fully comprehend how to get my errors, but I'm at a loss. When I debug my code, the catchError
in my effects class fires and sends off a LoadFail action, the reducer catches the action, sets the error and returns the state. However, on my subscription side of things in MyClass
, I never see anything. I figure I must be missing something critical here, but all my Googling expertise has left me empty handed and I figured I'd brave Stack Overflow and beg for its wisdom on the matter.
tl;dr: My store works just fine when the server responds, but when it doesn't, my errors aren't being sent to the subscription of a store state observable.