首页 > 解决方案 > 如何处理 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 处理错误?

标签: angularredux

解决方案


最后我明白了。我们必须在效果、动作、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));
          }))));

推荐阅读