【问题标题】:How to set Django response status and error message and display it with AngularJS如何设置 Django 响应状态和错误消息并用 AngularJS 显示
【发布时间】: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


【解决方案1】:

我会查看响应中返回的特定错误,然后根据该消息显示相应的消息。如果服务器没有返回不同的消息,我会先纠正这个问题。如果不能,您可能需要实现更多客户端逻辑,例如在用户填写表单之前查看是否存在任何值并将它们设为只读或类似。

function(response){
    //could use case statements too instead of if statements.
    if(response.cantRememberVarName == "user id already exists"){
      $scope.errorPost = "Ooops User Id already exists";
    }
    if(response.cantRemberVarName == "phone number already exists"){
      ....
    }
    $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);
  });

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2015-04-20
  • 2014-09-10
  • 1970-01-01
  • 2017-11-07
  • 1970-01-01
  • 2016-10-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多