【问题标题】:Handle multiple post and retrieve data with angularJs使用 angularJs 处理多个帖子并检索数据
【发布时间】:2016-04-04 15:10:09
【问题描述】:

我在使用 AngularJS(我正在使用 Ionic)执行异步调用时遇到问题。 我已将数据存储在$localStorage 中。然后有一个函数将所有数据发送到服务器。问题是在来自 http POST 请求的错误回调的情况下将它们存回。 有我的代码:

var data = $localStorage.prelevement.environement;
for (var j = 0; j < data.length; j++) {
    $http.post("http://localhost:3000/prelevement/environement", data[j]).then(
    function (res){},
    function (err) {
      $localStorage.prelevements.environement.push(data[j]);
    });
  }

关键是当第一个回调发生时,for循环已经完成并且j = data.length + 1所以我得到了一个错误,因为data[j]undefined

有没有办法在我的回调函数中捕获发送的数据或有什么想法来处理这个问题?

【问题讨论】:

  • 您是否尝试过为每次通话设置 $timeout/setTimeout?
  • 在我看来,将$http 部分移动到接受该值作为参数并在循环中使用它的函数中。这里使用函数的原因是为了获得闭包的好处。

标签: javascript angularjs http post asynchronous


【解决方案1】:

$localStorage.prelevement.environement; 包装在一个promise 中,然后执行其余代码。记得在你的构造函数中引用$q

var dataPromise = $q.when($localStorage.prelevement.environement); // returns a promise

dataPromise.then(function(){ // resolve the promise in the successcallback using then()
  for (var j = 0; j < data.length; j++) {
        $http.post("http://localhost:3000/prelevement/environement", data[j]).then(
        function (res){},
        function (err) {
          $localStorage.prelevements.environement.push(data[j]);
        });
      }
});

【讨论】:

    【解决方案2】:

    我找到了答案,我将它包装在一个匿名函数中:

    var data = $localStorage.prelevement.environement;
    for (var j = 0; j < data.length; j++) {
        (function(i){
             $http.post("http://localhost:3000/prelevement/environement", data[j]).then(
                 function (res){},
                 function (err) {
                     $localStorage.prelevements.environement.push(data[j]);
             });
        })(j)
      }
    

    感谢您的所有回答! :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-25
      • 2023-03-06
      • 1970-01-01
      • 2013-12-02
      • 1970-01-01
      相关资源
      最近更新 更多