如何在1.5版本中以$ angularjs取消承诺
我使用的是角度1.5.7,如果需要时间取消资源上的删除。 我正在使用MEAN堆栈,有时候我看到资源上的删除被视为挂起(是mongo,这很慢?)。 下面是工厂和控制器的片段,我称之为删除:*工厂:
.factory('addressesFactory', ['$resource', 'baseURL', function ($resource, baseURL) {
return $resource(baseURL + 'addresses/:id', {id: '@_id'}, {
'update': {
method: 'PUT'
},
'delete': {
method: 'DELETE'
}
});
}])
来自控制器的片段:
$scope.delete = function (address, addressesList) {
$scope.deleteDisabled=true;
console.log('[ModeratorsCtrl] Deleting:' + address.name);
console.log('[ModeratorsCtrl] ' + addressesList.length);
addressesFactory.delete({id: address._id}).$promise.then(
function (response) {
$scope.deleteDisabled=false;
console.log('[ModeratorsCtrl] Address deleted successfully');
},
function (response) {
$scope.deleteDisabled=false;
var message = '[ModeratorsCtrl] Error: ' + response.status + ' ' + response.statusText;
console.log(message);
}
);
};
我看到这篇文章如何取消$资源请求,并阅读有关取消请求:https://docs.angularjs.org/api/ngResource/service/$resource#! 与$ cancelRequest(),但我有点困惑。 任何人都可以给我关于我如何在我的实施中取消承诺的最佳实践? 问候,
可以说你的资源是Users
,要取消请求,你应该命名你的行为,例如
var request = Users.query();
在这一点上```请求是一个承诺。 你可以简单地做一个,
request.$cancelRequest();
取消。
感谢我的帮助,结果我在工厂做了以下工作:
.factory('addressesFactory', ['$resource', 'baseURL', function ($resource, baseURL) {
return $resource(baseURL + 'addresses/:id', {id: '@_id'}, {
'update': {
method: 'PUT'
},
'delete': {
method: 'DELETE',
cancellable: true
}
});
}])
那么在我的控制器中:
$scope.delete = function (address, addressesList) {
$scope.deleteDisabled = true;//prevent multiple click
var deleteRequest = addressesFactory.delete({id: address._id});
deleteRequest.$promise.then(
function (response) {
$scope.deleteDisabled = false;
console.log('[ModeratorsCtrl] Address deleted successfully');
},
function (response) {
$scope.deleteDisabled = false;
var message = '[ModeratorsCtrl] Error: ' + response.status + ' ' + response.statusText;
console.log(message);
}
);
$timeout(function () {//2 seconds then cancel the promise
if ($scope.deleteDisabled === true) {
console.log('[ModeratorsCtrl] Cancel ...');
deleteRequest.$cancelRequest();
$scope.deleteDisabled = false;
}
}, 2000);
};
希望这坚持最佳实践,随时给你的反馈。
链接地址: http://www.djcxy.com/p/77655.html上一篇: how to cancel a promise with $resource in angularjs in 1.5