Server side errors handling with angular-formly

二次信任 提交于 2020-01-06 23:53:01

问题


I'm looking for solution on how I can display errors that the server respond, this is the respond for every invalid submission so I want to make the error handler in the app level and not in a controller. I want to display the errors both on the FORM level and on the field level.

I have a REST API that in case of error return the following JSON object:

{
  "message": "Validation error: Validation notEmpty failed,\nValidation error: Validation isEmail failed",
  "errors": [
    {
      "field": "username",
      "message": "Validation notEmpty failed"
    },
    {
      "field": "email",
      "message": "Validation isEmail failed"
    }
  ]
}

How can I create a service that display the errors in case there is any?

Thanks


回答1:


So, i created this for another answer. Let me know if this sort of a setup works for you. Here, the error is intended to be displayed on response from the server after button click. You can modify it accordingly.

I have given the field a custom template as follows:

 formlyConfigProvider.setWrapper({
      name: 'inputWrapper',
  template: '<div ng-class="to.changeColor==\'red\'? \'redBorder\' : \'otherBorder\'"><formly-transclude></formly-transclude>{{to.keyVal}}</div>'
    });

The form elements are defined through a schema format to allow each element to be individually accessed.

vm.schema={
    "schema": {
        "coolValue" : [{
                "key": "coolValue",
                "type": "input",

          "wrapper": ['inputWrapper'],
                "templateOptions": {
                   "type" : "text",
                  "label": 'Cool Value',
                  "keyVal":"",
                  "changeColor":"green"
                }

         }]


    }

};

Finally, the onSubmit function

function onSubmit() {

//Do whatever you want here
//Let's say your server returns an error "iNVALID Credentials"
   var response={
  "error": {
    "errors": [
      {
        "domain": "global",
        "reason": "authError",
        "message": "Invalid Credentials",
        "locationType": "header",
        "location": "Authorization",
      }
    ],
    "code": 401,
    "message": "Invalid Credentials"
  }
};
vm.schema.schema.coolValue[0].templateOptions.changeColor="red";
      vm.schema.schema.coolValue[0].templateOptions.keyVal=response.error.message;

    }
  });

You can essentially pass any error message or response from the server here.

The CSS contains a class to add a red border to the field.You are free to disable this.Feel free to ping if you need anything in this area as well.

Here is a DEMO



来源:https://stackoverflow.com/questions/37142570/server-side-errors-handling-with-angular-formly

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