我在一个有角度的项目中工作,我有一个网格,里面有一些数据和一些动作。
单击onclick函数中的一个操作时,ajax请求将进入服务器端,该请求在生命周期过程中一次。
但是当用户在第一个请求的响应出现之前连续单击操作按钮时,同一个呼叫将多次进入服务器,最终会出错。
我试图在ajax请求之前禁用操作按钮,即使我无法阻止多个请求。有没有办法阻止第二次请求?
我的代码是
$http({
method: 'POST',
url: urls.api_url_serv + 'notification/read?token=' + token,
transformRequest: transformRequestAsFormPost,
withCredentials: false,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: {
notification_id: notification_id
}
}).then(function(response) {
var data = response.data;
//Some actions
}).catch(function(response) {
var status = response.status;
// Some actions
});
<span ng-class="{'disabled': read_disable}">
<i class="fa fa-envelope" ng-click="MarkAsReadNotification(row.id)"></i>
</span>
答案 0 :(得分:0)
this
)
this.makeRequest = () => {
if (!this.request) {
this.request = $http({
method: 'POST',
url: urls.api_url_serv + 'notification/read?token=' + token,
transformRequest: transformRequestAsFormPost,
withCredentials: false,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: { notification_id }
});
this.request.success((data) => {
// If you want let the user do a request, after this one is finished
this.request = undefined
})
}
}
答案 1 :(得分:0)
要停用按钮,请使用ng-disabled directive:
<button ng-click="submit()" ng-disabled="disableButton">
Submit
</button>
$scope.submit = function() {
$scope.disableButton = true;
return $http(config)
.then(function(response) {
var data = response.data;
//Some actions
return response.data;
}).catch(function(response) {
var status = response.status;
// Some actions
throw response;
}).finally(function() {
$scope.disableButton = false;
});
};
在启动XHR之前禁用该按钮。当请求达成或被拒绝时,使用.finally
块重新启用按钮。