angular - NgRx - 从后端获取错误验证并传递给组件

我试图从 api 中获取错误消息并显示在我的表单输入中,以便用户可以看到正在提交的数据有什么问题。

来自 API 的响应:

{
  "message": "The given data was invalid.",
  "errors": {
    "name": [
      "This name is already in use."
    ]
  }
}

用户表单.component.ts

this.store.dispatch(new actions.CreateUser(user));

用户效果.ts

@Effect()
  CreateUser$: Observable<Action> = this.actions$.pipe(
    ofType(UserActions.CREATE_USER),
    map((action: UserActions.CreateUser) => action.payload),
    switchMap(payload => {
      return this.userService.save(payload).pipe(
        map((user: User) => {
          return new UserActions.CreateUserSuccess(user);
        }),
        catchError(err => {
          return of(new UserActions.CreateUserFail());
        })
      );
    })
  );

我如何获取该错误并将其传回我的组件?

我是否应该喜欢效果内部并将其订阅到等待 CreateUserFail 错误的操作?我不确定这是否是一个好的做法,因为它会监听所有类型的 Action。

最佳答案

我们构建了一个选择器并订阅了该选择器。

效果

  @Effect()
  createProduct$: Observable<Action> = this.actions$.pipe(
    ofType(productActions.ProductActionTypes.CreateProduct),
    map((action: productActions.CreateProduct) => action.payload),
    mergeMap((product: Product) =>
      this.productService.createProduct(product).pipe(
        map(newProduct => (new productActions.CreateProductSuccess(newProduct))),
        catchError(err => of(new productActions.CreateProductFail(err)))
      )
    )
  );

reducer

case ProductActionTypes.CreateProductFail:
  return {
    ...state,
    error: action.payload
  };

选择器

export const getError = createSelector(
  getProductFeatureState,
  state => state.error
);

组件

// Watch for changes to the error message
this.errorMessage$ = this.store.pipe(select(fromProduct.getError));

模板

<div *ngIf="errorMessage$ | async as errorMessage" class="alert alert-danger">
  Error: {{ errorMessage }}
</div>

您可以在此处找到完整示例:https://github.com/DeborahK/Angular-NgRx-GettingStarted/tree/master/APM-Demo4

https://stackoverflow.com/questions/54830947/

相关文章:

arrays - Julia - 许多分配以浏览结构中的数组

django - 从 Django 模型中的选择中获取人类可读名称的实际值

jquery - 我试图让这个光标效果对 react

c++ - 为什么 mersenne_twister_engine 保证某些结果?

r - 无法安装 tidyverse

r - 你能在 RMarkdown 中左对齐或加粗 Kable 的表格/图形标题吗?

spring-boot - 如何将base64转换为java中的MultipartFile

python - 无法安装 Python secret 包

r - 从分布到置信区间的寓言

haskell - 了解如何应用 haskell 应用仿函数