angularjs - 从指令调用 $http 在 angularjs watch 中
问题描述
我试图在我的指令中从手表内部调用 $http 服务。假设,该指令被放置在多个输入元素上。如果所有元素的值一起改变,手表会背靠背触发,$http 也会被背靠背调用,有时会弄乱每个 $http 调用的响应,即连续的 $http 调用,即使输入不同反应是一样的。为这种情况构建代码的正确方法是什么?我可以使用承诺来解决这个问题。如果是,那么如何,考虑到这是相同的 $http 调用,被不同的输入调用。
Utils.directive('setDescription', function ($q,$http,$timeout) {
var directive = {};
directive.priority = 1;
directive.restrict = 'A';
directive.require = 'ngModel';
directive.link = function(scope,element,attributes,ngModel) {
scope.isInput = false;
scope.getDescription = true;
scope.elementArray = [];
element.bind("keypress", function (event) {
scope.isInput = true;
return true;
});
scope.$watch(function(){
var codeElem = element.next();
if(codeElem[0]!=undefined){
codeElem=codeElem[0];
}
return scope.gettheObject(codeElem.name,scope);
},function(newValue,oldValue){
if(!scope.isInput && scope.getDescription){
if(newValue!=undefined && (newValue.trim())!=""){
$timeout(function() {
element.val(newValue);
scope.elementArray.push(element);
$http({
method: 'POST',
url: Constants.BASE_REST_URL + '/picklist/pickListResultGeneric',
data : CryptoHelperService.getEncryptedData(searchstr,true),
headers: CryptoHelperService.getEncryptionHeaders(),
cache: false,
xsrfCookieName : 'nicAccessCookie'
}).then(function(response) {
response.data = CryptoHelperService.getDecryptedResponse(response.data,response.headers);
});
});
}
}
});
}
return directive;
});
解决方案
在 promise 的帮助下解决了。使用$q.when()
(与 相同$q.resolve()
),创建一个立即使用给定值解决的承诺。对于数组中的每个元素,$http
都会构造调用并将其添加到承诺链中。一旦所有元素都被迭代,每个调用都会按照它们在链中添加的顺序被调用。
var promiseChain = $q.when();
scope.elementArray.forEach(function(elem) {
//Initiate a chain of promises for each REST call
promiseChain = promiseChain.then(function() {
return $http({
method: 'POST',
url: someURL,
data : someData
});
});
//Each promise in the chain is then resolved individually in the order in which they were invoked.
promiseChain.then(function(response) {
//do stuff here after each call returns individually
});
});
推荐阅读
- python - 如何使用子图和 Seaborn Lineplot 仅在图外的框中显示图例?
- node.js - 加入多个集合 + docDB
- java - 如何从 IloModeler 或 IloCplex 获取所有 IloNumVar
- perl - 如何在 Perl 中以命令行选项格式将列表作为输入
- mysql - 如何将集合存储在数据库中?
- azure-devops - Azure devops rest api,如何修改一个值
- java - RabbitMQ 在发送消息到交换时返回 MQ_UNBOUND_QUEUE
- spring - 从 PropertySource Springboot 迭代属性
- compression - 将 DeflaterOutputStream 转换为 ByteArrayOutPutStream
- time-series - 如何提高 rnn 和 LSTM 的准确率?