如何呈现错误客户端? AngularJS /的WebAPI的ModelState [英] How to render errors to client? AngularJS/WebApi ModelState
问题描述
我在建设有针对的WebAPI后端的AngularJS SPA的应用程序。我使用模型验证属性在服务器上,如果验证失败,这是我从返回的ModelState
{消息:请求是无效的。,ModelState中:{model.LastName:姓必须至少有2个长字符。] }}
我如何再与AngularJS呈现此给客户?
//保存用户信息
$ scope.processDriverForm =功能(的isValid){
如果(的isValid){
//设置按钮无效,图标,文字
$ scope.locked = TRUE;
$ scope.icon ='发发微调发旋';
$ scope.buttonText ='保存...;
$ scope.submitted = TRUE;
$ scope.formData.birthDate = $ scope.formData.birthMonth +'/'+ $ scope.formData.birthDay +'/'+ $ scope.formData.birthYear;
$ HTTP({
方法:POST,
网址:'API /帐号/注册,
数据:$ .PARAM($ scope.formData)
标题:{内容类型:应用程序/ x-WWW的形式urlen codeD'} //设置标题等等角度传递信息的表格数据(而不是请求负载)
})
.success(功能(数据){
的console.log(数据);
toastr.success(用户+ $ scope.formData.username +'创建!');
$ scope.userForm $ setPristine()。
$ scope.formData = {};
//复位按钮
$ scope.locked = FALSE;
$ scope.icon ='';
$ scope.buttonText ='保存';
//重新提交验证
$ scope.submitted = FALSE;
})
.error(功能(数据,响应){
的console.log(数据);
toastr.error('!哎呀有一个错误创建用户再试一次,如果问题仍然存在,请联系技术支持。');
//复位按钮
$ scope.locked = FALSE;
$ scope.icon ='';
$ scope.buttonText ='保存';
$ scope.submitted = FALSE; VAR RESP = {}; 变种错误= [];
对(在resp.ModelState VAR键){
对于(VAR I = 0; I< resp.ModelState [关键]。长度;我++){
errors.push(resp.ModelState [关键] [I]);
}
}
$ scope.errors =错误; }); }
其他{
toastr.warning(无效的用户表单,纠正错误,再试一次。);
}
};
让你到你的服务器呼叫时,捕捉基于甩在 $ HTTP
许的错误
然后在你的控制器我建议压扁于错误显示的处理错误的数组的答复,如在此小提琴例如:
为(以resp.ModelState VAR键){
对于(VAR I = 0; I< resp.ModelState [关键]。长度;我++){
errors.push(resp.ModelState [关键] [I]);
}
}
要放在一起:
//张贴数据到Web API /服务
$ http.post(URL数据)
.success(successHandler)
.error(功能(响应){
//当有一个错误,分析错误
//并将其设置为范围(绑定)
$ scope.errors = parseErrors(响应);
});//解析错误的方法分离成一个单一的平面数组
功能parseErrors(响应){
变种错误= [];
对(在response.ModelState VAR键){
对于(VAR I = 0; I< response.ModelState [关键]。长度;我++){
errors.push(response.ModelState [关键] [I]);
}
}
返回错误;
}
I'm building an AngularJS SPA application with WebApi for the backend. I am using attributes for model validation on the server, if validation fails this is what I return from the ModelState.
{"Message":"The request is invalid.","ModelState":{"model.LastName":["Last Name must be at least 2 characters long."]}}
How do I then render this to the client with 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.');
}
};
When making your call to your server, capture the error based upon the rejection of the $http
promise.
Then in your controller I would suggest flattening the response to an array of errors upon handling of the error for display as shown in this fiddle example:
for (var key in resp.ModelState) {
for (var i = 0; i < resp.ModelState[key].length; i++) {
errors.push(resp.ModelState[key][i]);
}
}
To put it all together:
// 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 /的WebAPI的ModelState的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!