Get error response from ngrx@effects to component

狂风中的少年 提交于 2021-01-27 07:10:47

问题


I need to set server error validation for every input field in form. Problem is, I use ngrx@store and in effect I have

 @Effect({ dispatch: false })
  error$ = this.actions$.pipe(
    ofType(actions.UserActionTypes.Error),
    map(
      (error: actions.Error) => {
        new actions.Error(error);
      }
      //this.notificationService.warn(error.error.message)
    )
  );

With this code, I store errors to store.

Now I need to get these errors in my component, where I want to check for which input field I get an error, and set error to HTML next to the selected field.

    this.errorsMsgs$ = this.store.select(fromStore.UserSelectors.getErrors);
    this.errorsMsgs$.pipe(takeUntil(this.destroy$)).subscribe((error: any) => {
      console.log(error);
      for (let err of error) {
        if (err.field === "username") {
          this.usernameError = err.defaultMessage;
        }
        if (err.field === "lastName") {
          this.lastNameError = err.defaultMessage;
        }
        if (err.field === "firstName") {
          this.firstNameError = err.defaultMessage;
        }
        if (err.field === "email") {
          this.emailError = err.defaultMessage;
        }
        if (err.field === "phone") {
          this.phoneError = err.defaultMessage;
        }
        if (err.field === "enabled") {
          this.enabledError = err.defaultMessage;
        }
      }
    });

The problem is if I put this code in ngOnInit, I get an error in the console because the errors doesn't exist yet.

ERROR TypeError: error is not iterable

Function for CRUD is in ngrx@effect and there is success end error... How to know In component when the submit method have an error response and when I need to call this method in component for errors?

Is there any way to call this method in component from effects?

Here is error response:

{
  "timestamp": "2020-01-14T11:37:51.533+0000",
  "status": 400,
  "error": "Bad Request",
  "errors": [{...}
  ],
  "message": "Validation failed for object='user'. Error count: 6",
  "path": "/user/add/"
}

回答1:


You can simply subscribe to the actions observable chanel, and just filter it the excepted action whit the ofType() operator function in the component. Ex: ngOnInit(){ this.actions$.pipe(ofType(action)).subscribe(action => console.log(action.payload)); }. You need inject the actions$ observable in the constructor, from import { Actions} from '@ngrx/effects';. Or if you want to save this result in the store, just use reducer, and after this select the excepted values from store.



来源:https://stackoverflow.com/questions/59733083/get-error-response-from-ngrxeffects-to-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!