angular - 如何处理 redux 中的成功和失败
问题描述
插入 redux 时如何处理错误?我的代码:
async newGroup(item: Item) {
const newGroup = new GenericEntity(null, item.text, item.textMultiLanguage);
this.store.dispatch(new RequestAddWorkstationGroup(newGroup));
this.messageNotify.open(this.translate.instant('common.created_ok'), 'X', true, true, 3000, 'end', 'top', true, 'success');
}
我想在正确插入元素时显示一条通知消息,并在用户尝试插入元素时在元素出错时显示另一条消息。
有没有办法使用 store-redux 处理错误?
解决方案
最后我明白了。我们必须在效果、动作、reducers 文件中设置处理错误。
在行动中,我必须添加:
export class CategoryFailed implements Action {
static readonly TYPE = 'CATEGORY_FAILED';
readonly type = CategoryFailed.TYPE;
constructor(public category: GenericEntity) { }
}
export class RequestCategoryFailed implements Action {
static readonly TYPE = 'REQUEST_CATEGORY_FAILED';
readonly type = RequestCategoryFailed.TYPE;
constructor(public category: GenericEntity) { }
}
在减速器中:
case CategoryFailed.TYPE: {
return { ...state, categories: state.categories.map(it => it.id === action.category.id ? it : it) };
}
......TYPE:
case RequestCategoryFailed.TYPE:
default: { return { ...state }; }
在效果:
@Effect() requestCategoryGroup: Observable<Action> = this.actions.pipe(
ofType<RequestCategoryGroup>(RequestCategoryGroup.TYPE),
mergeMap((category) =>
from(this.Service.category(category.category)).pipe(
map(() => new category(category.category)),
catchError((error) => {
const message = JSON.parse(error.response);
this.dialogsService.alert(this.translate.instant('common.cannot_modify'), message.Title);
return of(new CategoryFailed(category.category));
}))));
推荐阅读
- amazon-web-services - Ansible 2.5.2,AWS Lambda,想要创建一个模板,无论我是否分配了子网或安全组
- python - 这个比较器功能可以用等效的键功能代替吗?
- typescript - 打字稿覆盖泛型方法
- mysql - mysql select query where date = ... 不返回数据
- java - 永远不要在 Android SQLite 中输入 cursor.moveToNext()
- python - 如何在 Python 中编码 Unicode 对象?
- json - 在 vs-code 中的 JSON 中,如何为数组中的字符串赋予与对象中的字符串不同的颜色?
- visual-studio - Visual Studio 将 npm 包显示为未安装
- java - 具有相同数据的两个数据库,报告的时间不同
- excel - 是否有一个 Excel 公式可以根据从 TRUE 到 FALSE 的变化提供单元格位置?