简体   繁体   English

如何在Angular JS中发布同步http请求

[英]how to post synchronous http request in angular js

How to post synchronous ajax request or how to set async as false in angular $http service . 如何在angular $ http service中发布同步ajax请求或如何将async设置为false。

Example of my service is 我的服务示例是

$http.post("qa.test.net/rest/customtableitem.profile.interests?format=json", JSONobject)

My controller is 我的控制器是

for (var i = 0; i < Insert.length; i++) 
{
   if (Insert[i].ItemID == null) 
   {
      TestInterestService.insertTest(Insert[i]).success(function (data) {
      }).error(function (data) {
      });
    }
   }

In this data is getting inserted asynchronously not in order for that reason it is messing the order entered I want to insert in synchronous manner. 在这种情况下,数据不是以异步方式插入的,原因是它弄乱了我想以同步方式插入的输入顺序。 Any suggestions 有什么建议么

EDIT That did not solved my problem, I was looking for pointing to the service where we can sent async as false in request headers. 编辑那并没有解决我的问题,我一直在寻找指向我们可以在请求标头中以false形式发送异步信息的服务。

As Ben Lesh pointed in his answer to How to $http Synchronous call with AngularJS you cannot perform not async call with $http service. 正如Ben Lesh在他对如何使用AngularJS进行$ http同步调用的 回答中指出的那样您无法使用$http服务执行非异步调用。

However as an alternative you can replace for loop to while loop, condition is until Insert array not empty, prior starting while loop create flag variable which would be boolean identifier that ajax success handler finished and next ajax can be sent. 但是,您也可以将for loop替换for loop while循环,条件是直到Insert数组不为空,然后再开始while循环创建flag变量,该变量将是ajax成功处理程序完成并且可以发送下一个ajax的布尔标识符。 See code below with commented changes : 请参阅以下带有注释性更改的代码:

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;
     }
  }
}

Good Luck ! 祝好运 !

use async Library 使用异步

link : https://www.npmjs.com/package/async 链接: https : //www.npmjs.com/package/async

Example

 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 

});

For simple use cases, you can leverage promises, when one request has successfully resolved, only .then send another one 对于简单的用例,您可以利用诺言,当一个请求成功解决后,仅发送.then发送一个

MyService.postMe().then(function(response) {
    MyService.postMeToo(response.data);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM