代码之家  ›  专栏  ›  技术社区  ›  Nagesh

消费webapi后角度模型错误的解包与解析

  •  0
  • Nagesh  · 技术社区  · 7 年前

    {
    "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"
        ]
    }
    

    }

    当webapi返回错误请求时,将返回上述模型错误。我想解析这些错误,并在网页中连续显示它们,如下图所示: Errors to be displayed after the form is posted

    我确实试过:

    var obj = JSON.parse(modelErrors);
    

    但我无法读取obj的数据。我想要一个Angular2+的通用代码片段。

    1 回复  |  直到 7 年前
        1
  •  1
  •   bgraham    7 年前

    我假设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);
             }
          }
    }
    
    推荐文章