目前,我的代码片段就像当错误发生时,它通过一条消息,几秒钟后消失,我用$timeout完成了它,即使成功响应,成功消息也会在几秒钟后出现并消失。但出于某些原因,我现在不需要这样。
这是我当前的片段:
$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);
});在上面的片段中,如果我不使用$timeout,那么成功和错误就会同时存在。
例如:用户提交错误数据并得到错误消息后,提交正确的数据并获得成功消息,此时屏幕上存在成功和错误消息,这个模糊的。
我想要的是,当成功消息出现时,它应该存在于屏幕上,如果以后再次出现错误消息,成功消息应该消失并出现错误消息。
可选:
在这里,您将看到如何在模板中使用:
<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-->希望你有了这个问题:
发布于 2019-05-23 21:59:38
如果我不使用
$timeout,那么成功和错误就会并存。
响应和拒绝处理程序可以调用公共函数。
$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;
});然后将公共代码放在公共函数中:
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);
}模板可以简化:
<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>https://stackoverflow.com/questions/56276940
复制相似问题