Angular2 + ngrx/store用于处理失败的HTTP请求 [英] Angular2 + ngrx/store for handling failure HTTP requests
问题描述
我想有一个简单的代码路径来创建和调度HTTP动作.我想做的是这样的:
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));
这样,成功和失败响应都将转换为JSON,然后根据成功/失败标准分配正确的归约类型,以便可以正确地操作存储. (请考虑用户登录成功和失败,并返回200或401).
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).
有没有更清洁或更完善的方法来处理此问题?当前的第二个.catch
不能正常播放,因为它没有返回可观察到的声音.
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?
推荐答案
在我的一项服务中,我这样做是这样的:
In one of my services I do it like this:
get(url, actionType) {
this._http.get(BASE_URL + url)
.map(response => response.json())
.map(payload => ({ type: actionType, payload }))
.subscribe(action => this.store.dispatch(action), error => this._apiErrorHandler(error));
}
private _apiErrorHandler(response) {
let payload = response.json().error;
this.store.dispatch({ type: 'API_ERROR', payload });
}
这篇关于Angular2 + ngrx/store用于处理失败的HTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!