AngularJS handling $http Error/Success in Smart Way

后端 未结 1 1682
时光说笑
时光说笑 2020-12-12 03:58

Currently my snippet works like when an Error occurs, it through a message and disappear after a few second, i did it with $timeout and even if success response

相关标签:
1条回答
  • 2020-12-12 04:23

    if i wouldn't use $timeout then success and error are would exist together.

    The response and rejection handlers can call a common function

    $http.post('http://127.0.0.1:8000/api/v1/contact/', $scope.formModel)
      .then(function(response) {
        displayMessage("success",response);
        return response;
    }, function(response){
        displayMessage("error",response);
        throw response;
    });
    

    Then put common code in the common function:

    var timeoutId;
    function displayMessage(type,response) {
        var success = (type == "success");
        $scope.messageClass = success ? "alert-success" : "alert-danger";
        var messageDuration = success ? 6000 : 3000;
    
    
        if (success) {
            $scope.messageText = "Contact successfully saved.";
        } else if (response.status == 500) { 
            $scope.messageTest = "Oops, Internal Server Error";
        } else {
            $scope.messageText = "Oops, YOU DID SOMETHING WRONG!!!!";
        };
    
        //cancel previous timeout
        timeoutId && $timeout.cancel(timeoutId);
    
        timeoutId = $timeout(function() {
            $scope.messageText = "";
        }, messageDuration);
    }
    

    The template can be simplified:

    <div class="alert" ng-class="messageClass" ng-show="messageText">
      <p> {{ messageText }} </p>
      <strong>UserID :</strong>{{ userid }} <br>
      <strong> Name :</strong>{{ name }} <br>
      <strong> Email :</strong>{{ email }} <br>
      <strong> Phone :</strong>{{ phone }} <br>
      <a href="#!/crud" class="btn btn-primary">Show Me All Contacts</a>
    </div>
    
    0 讨论(0)
提交回复
热议问题