如何在angular js中发布同步HTTP请求
how to post synchronous http request in angular js
如何发布同步ajax请求或如何在angular $http service中设置async为false。
我的服务示例是
$http.post("qa.test.net/rest/customtableitem.profile.interests?format=json", JSONobject)
控制器是
for (var i = 0; i < Insert.length; i++)
{
if (Insert[i].ItemID == null)
{
TestInterestService.insertTest(Insert[i]).success(function (data) {
}).error(function (data) {
});
}
}
这个数据是异步插入的,不是按顺序插入的,因为它扰乱了我想以同步方式插入的顺序。任何建议
编辑这并没有解决我的问题,我正在寻找指向服务,我们可以在请求头中发送async作为false。
正如Ben Lesh在他的回答中指出的,如何使用AngularJS进行http同步调用,你不能使用$http
服务执行非异步调用。
然而,作为一种替代方法,你可以将for loop
替换为while循环,条件是直到插入数组不空,之前启动while
循环创建flag
变量,这将是ajax成功处理程序完成的布尔标识符,下一个ajax可以发送。请看下面带有注释的代码:
var flag = true;
var length = Insert.length;
while (length){
if(flag){
var item = Insert[--length];
// Set flag to false, until success executed
flag = false;
TestInterestService.insertTest(item).success(function( path ){
// We are ready to perform next ajax, set flag to true.
flag = true;
}).error: function( path ){
// Error or not we have to set flag to true to allow further iterating
flag = true;
}
}
}
祝你好运!
use async Library
链接:https://www.npmjs.com/package/async
async.each(Insert, function (insert_record_objec, callback) {
TestInterestService.insertTest(insert_record_objec).success(function (data) {
callback();
}).error(function (data) {
callback();
});
}, function (err) {
// if any of the processing produced an error
});
对于简单的用例,您可以利用承诺,当一个请求成功解决时,只有.then
发送另一个
MyService.postMe().then(function(response) {
MyService.postMeToo(response.data);
});
相关文章:
- 根据最新响应在 Node 中发送同步请求
- 同步请求谷歌地图地理编码
- 火狐插件 SDK 同步请求
- 以发送的相同顺序显示 AJAX 响应,而不使用同步请求
- jquery 1.4,同步请求
- 如何为JQuery$.ajax同步请求设置超时并执行某些操作
- 节点4.2.0 phantom stdout:NETWORK_ERR:XMLHttpRequest异常101:同步请求中
- 正在包装主干同步请求
- RequireJS:同步请求文本内容
- mongodb同步请求
- Marketo-Munchkin同步请求损害了JS的性能
- 节点.js中的同步请求
- 循环中与 ajax 的同步请求
- 用于缓存的Node.js同步请求
- js 1.10, jquery 2.1和同步请求
- AJAX同步请求和操作,同时等待
- 我如何在主干运行一个基本的GET /同步请求
- 为什么异步xmlhttprequest优于同步请求?
- 使用JavaScript同步请求图像
- HTTP同步请求阻止我的GIF在Chrome和IE中移动