我有一个用于销售人员的api,它将返回这样的模型错误(提交失败时):
{
"Message": "The request is invalid.",
"ModelState": {
"sv.Name": [
"The field Name must be a string or array type with a minimum length of '3'."
],
"sv.Designation": [
"The field Designation must be a string or array type with a minimum length of '2'."
],
"sv.JoiningDate": [
"Value for JoiningDate must be between 1/1/2000 12:00:00 AM and 1/1/2019 12:00:00 AM"
],
"sv.IncentivePercent": [
"The field IncentivePercent must be between 0.01 and 999.99."
],
"sv.WarehouseID": [
"Please input a valid value for Warehouse"
]
}
}
当Web api返回错误请求时,将返回上述模型错误。我想解析这些错误,并在网页中依次显示它们,如下图所示:
我确实尝试过:
var obj = JSON.parse(modelErrors);
但是我无法从obj读取数据。为此,我需要Angular 2+中的通用代码段。
答案 0 :(得分:1)
我假设api返回500响应并带有那些模型错误?我会做这样的事情:
validationErrors = [];
this.myService.save(employee).subscribe(response => {
// The first parameter will be from any 200 codes, do what you want on success
},
err => {
// The second parameter will be from a 500 code, your error object
console.log(err); // Check out what the object looks like, usually what I want is in err.error;
this.validationErrors = [];
for (var errorArray in err.error.ModelState) {
if (err.error.ModelState.hasOwnProperty(errorArray )) {
this.validationErrors = this.validationErrors.concat(errorArray);
}
}
}