AngularJS 以智能方式处理 $http 错误/成功 [英] AngularJS handling $http Error/Success in Smart Way

查看:21
本文介绍了AngularJS 以智能方式处理 $http 错误/成功的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我的代码片段就像发生错误时一样,它通过一条消息并在几秒钟后消失,我用 $timeout 做到了,即使成功响应,成功消息也会出现并在之后消失几秒钟.但由于某些原因,我现在不需要这样.

这里是我当前的片段:

$http.post('http://127.0.0.1:8000/api/v1/contact/', $scope.formModel).then(功能(响应){$scope.successCallBack = '您已成功保存您的联系人';$scope.formModel = {};$超时(函数(){$scope.successCallBack = '';}, 6000);},功能(响应){//向用户显示发生了什么错误var errorData = response.data$scope.errorCallBack = Object.values(errorData)[0][0];$超时(函数(){$scope.errorCallBack = '';}, 3000);});

在上面的代码段中,如果我不使用 $timeout 那么成功和错误将同时存在.

例如:用户提交错误数据得到错误信息,提交正确数据得到成功信息后,此时屏幕上显示成功和错误信息,这很奇怪

我想要类似的东西,当成功消息出现时,它应该存在于屏幕上,如果稍后再次出现错误消息,成功消息应该消失并出现错误消息.

可选:

在这里你可以看到如何在模板中使用:

<p>{{ successCallBack }} </p><strong>用户 ID :</strong>{{ 用户 ID }} <br><强>名称:</strong>{{名称}}

<!--成功 div 结束--><div class="alert alert-danger" ng-if="errorCallBack"><!--( Error div start )如果在请求过程中发生任何错误,就会出现这个div--><p>糟糕!您无法保存此联系人!</p><p>原因,{{ errorCallBack }} </p><strong>用户 ID :</strong>{{ 用户 ID }} <br><强>名称:</strong>{{名称}}

<!--错误 div 结束-->

希望你有这个问题:

解决方案

如果我不使用 $timeout 那么成功和错误就会同时存在.

响应和拒绝处理程序可以调用一个通用函数

$http.post('http://127.0.0.1:8000/api/v1/contact/', $scope.formModel).then(功能(响应){displayMessage("成功",响应);返回响应;},功能(响应){displayMessage("错误",响应);抛出响应;});

然后把通用代码放在通用函数中:

var timeoutId;功能显示消息(类型,响应){var成功=(类型==成功");$scope.messageClass = 成功?警报成功":警报危险";var messageDuration = 成功?6000:3000;如果(成功){$scope.messageText = "联系人成功保存.";} else if (response.status == 500) {$scope.messageTest = "糟糕,内部服务器错误";} 别的 {$scope.messageText = "糟糕,你做错了!!!";};//取消之前的超时timeoutId &&$timeout.cancel(timeoutId);timeoutId = $timeout(function() {$scope.messageText = "";}, messageDuration);}

模板可以简化:

<p>{{ messageText }} </p><strong>用户 ID :</strong>{{ 用户 ID }} <br><强>名称:</strong>{{名称}}

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, a success message appear and disappear after a few second. but for some reasons, i dont need now like this.

here you go for my current snippet:

$http.post('http://127.0.0.1:8000/api/v1/contact/', $scope.formModel)
        .then(function(response) {
            $scope.successCallBack = 'You have successfully saved your contact';
            $scope.formModel = {};
            $timeout(function () {
                $scope.successCallBack = '';
            }, 6000);
        }, function(response){
            // Showing user exactly what error occurs
            var errorData = response.data
            $scope.errorCallBack = Object.values(errorData)[0][0];
            $timeout(function () {
                $scope.errorCallBack = '';
            }, 3000);
        });

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

for example: A user submit error data and he got error message and after he submit right data and got a success message, on that time success and error message are exist together on screen, this weired

I want something like, When success message appear, it should exist on the screen and if later again an error message occurrs, the success message should disappear and appear error message.

Optional:

Here you go to see how used in templates:

<div class="alert alert-success" ng-if="successCallBack">
  <p> {{ successCallBack }} </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> <!--sucess div ended-->

<div class="alert alert-danger" ng-if="errorCallBack"> <!--( Error div start )this div appear if any error occured during request-->
  <p>Oops! You can't save this contact !</p>
  <p> Cause,  {{ errorCallBack }} </p>
  <strong>UserID :</strong>{{ userid }} <br>
  <strong> Name :</strong>{{ name }} <br>
  <strong> Email :</strong>{{ email }} <br>
  <strong> Phone :</strong>{{ phone }} <br>
</div> <!--error div ended-->

Hope you got this issue:

解决方案

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>

这篇关于AngularJS 以智能方式处理 $http 错误/成功的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆