如何在angular js中发布同步HTTP请求

how to post synchronous http request in angular js

本文关键字:同步 请求 HTTP 布同步 angular js      更新时间:2023-09-26

如何发布同步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);
});