gpt4 book ai didi

angularjs - 如何向客户端呈现错误? AngularJS/Web Api 模型状态

转载 作者:行者123 更新时间:2023-12-03 23:28:21 25 4
gpt4 key购买 nike

我正在为后端构建一个带有 WebApi 的 AngularJS SPA 应用程序。我在服务器上使用属性进行模型验证,如果验证失败,这就是我从 ModelState 返回的内容。

     {"Message":"The request is invalid.","ModelState":{"model.LastName":["Last Name must be at least 2 characters long."]}}

然后我如何使用 AngularJS 将其呈现给客户端?
      //Save User Info
$scope.processDriverForm = function(isValid) {
if (isValid) {
//set button disabled, icon, text
$scope.locked = true;
$scope.icon = 'fa fa-spinner fa-spin';
$scope.buttonText = 'Saving...';
$scope.submitted = true;
$scope.formData.birthDate = $scope.formData.birthMonth + '/' + $scope.formData.birthDay + '/' + $scope.formData.birthYear;
$http({
method: 'POST',
url: 'api/Account/Register',
data: $.param($scope.formData),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
})
.success(function (data) {
console.log(data);
toastr.success('User ' + $scope.formData.username + ' created!');
$scope.userForm.$setPristine();
$scope.formData = {};
//reset the button
$scope.locked = false;
$scope.icon = '';
$scope.buttonText = 'Save';
//reset validation submitted
$scope.submitted = false;
})
.error(function (data, response) {
console.log(data);
toastr.error('Ooops! There was an error creating the user. Try again and if the problem persists, contact Support.');
//reset the button
$scope.locked = false;
$scope.icon = '';
$scope.buttonText = 'Save';
$scope.submitted = false;

var resp = {};

var errors = [];
for (var key in resp.ModelState) {
for (var i = 0; i < resp.ModelState[key].length; i++) {
errors.push(resp.ModelState[key][i]);
}
}
$scope.errors = errors;

});

}
else {
toastr.warning('Invalid User Form, correct errors and try again.');
}
};

最佳答案

调用服务器时,根据 $http 的拒绝捕获错误。 promise 。

然后在您的 Controller 中,我建议在处理显示错误时将响应对一系列错误进行展平,如 fiddle example 所示。 :

for (var key in resp.ModelState) {
for (var i = 0; i < resp.ModelState[key].length; i++) {
errors.push(resp.ModelState[key][i]);
}
}

把它们放在一起:
// Post the data to the web api/service
$http.post(url, data)
.success(successHandler)
.error(function (response) {
// when there's an error, parse the error
// and set it to the scope (for binding)
$scope.errors = parseErrors(response);
});

//separate method for parsing errors into a single flat array
function parseErrors(response) {
var errors = [];
for (var key in response.ModelState) {
for (var i = 0; i < response.ModelState[key].length; i++) {
errors.push(response.ModelState[key][i]);
}
}
return errors;
}

关于angularjs - 如何向客户端呈现错误? AngularJS/Web Api 模型状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23086664/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com