【发布时间】:2019-10-05 14:46:09
【问题描述】:
AngularJS 根据发生的确切情况向用户抛出错误消息
我使用 Django Rest Framework 构建的 API。
我的数据库中只有四个字段。
他们是,userid, name, email, phone
我写在这个 sn-p 下面,它可以很好地处理错误和成功:
$scope.formModel = {}; // It will post data and handle both success and error,
$scope.onSubmit = function () {
$http.post('http://127.0.0.1:8000/api/v1/contact/', $scope.formModel)
.then(function(response){
$scope.successPost = 'You have successfully submitted your Contact';
$timeout(function(){
$scope.successPost = '';
},4000);
$scope.contacts.push(response.data);
}, function(response){
$scope.errorPost = 'Ooops! It seems Your Submitted User ID or Phone Number or Email are already exist, please try again with different data';
$timeout(function(){
$scope.errorPost = '';
},10000);
});
$scope.formModel = {};
$scope.addContactForm.$setPristine();
};
我的后端不允许发布任何重复的项目,例如如果数据库中存在电话号码,第二次,用户无法发布此内容,如果他们尝试发布已经存在的电话号码,我想要向他们显示 “您提交的电话号码已经存在” 的消息同样,如果他尝试提交已经存在的电子邮件,我想向他显示类似 “您提交的电子邮件已经存在”的消息"
目前我的 sn-p 的工作方式就像他是否可以成功发布,他会收到成功消息,如果有错误,他会收到一条错误消息,但我想准确显示发生了什么以及为什么不被接受。
【问题讨论】:
-
状态码在 200-299 范围之外的 HTTP 响应进入 $http 服务拒绝处理程序。后端需要适当设置状态码和消息。
标签: angularjs django-rest-framework