I want to have a simple code path for creating and dispatching HTTP actions. What I would like to do is something like:
this.http.request(...)
.map((res: Response) => res.json())
.catch((err: any) => err.json())
.map((payload: any) => { type: 'SUCCESS', payload })
.catch((payload: any) => { type: 'FAILURE', payload})
.subscribe((action: Action) => this.store.dispatch(action));
That way both the success and failure responses are converted to JSON and then based upon the success/fail criteria assign the correct reduction type so that the store can be operated on properly. (think user login success and failure which returns a 200 or 401).
Is there a cleaner or better way of handling this? Current the 2nd .catch
doesn't play well since it is not returning an observable.
Suggestions or other solutions welcome?
From the example-app from
ngrx
, for this case is recommended to use @Effects(check the docs folder), and IMO, is a more clear way, check the service:And check the Effect:
Off course, you need to setup the Effects on appModule:
Read more about ngrx/effects on the docs folder from the repo.
In one of my services I do it like this: