質問

IDの配列を持ち、それらを繰り返し、それらをサービスに渡してデータを取得します。しかし、以前のIDの処理が終了した後に次のIDに移動します。すべてのデータがフェッチされた後、特定の機能を呼び出す必要があります。

私のコード(繰り返しなし)Woldは

のようなものになる
MyService.fetch(id)
        .success(function (data, status, headers, config) {
            doSomething();
        });
.

私が達成したいのはこのようなものですが、私のIDの配列内の未知数のアイテムを扱うことができる方法で:

MyService.fetch(id).success(function (data, status, headers, config) 
{
   MyService.fetch(id2).success(function (data, status, headers, config) 
   {
     doSomething();
   });
});
.

どんなアイデアも達成する方法?

ありがとう

トーマス

役に立ちましたか?

解決

角度にはLite Promish Libraryが付属しています。 $ Q 。 それは実際にはやるのがとても簡単です。

サービス

myApp.factory('theProcessor', function($q, $timeout) {

  return {
    fetch: function(queue, results, defer) {

      defer = defer || $q.defer();

      var self = this;  

      // Continue fetching if we still have ids left

      if(queue.length) {

        var id = queue.shift();

        // Replace this with your http call
        $timeout(function() {
          // Don't forget to call d.resolve, if you add logic here 
          // that decides not to continue the process loop.
          self.fetch(queue, results, defer);
          results.push({ id: id, value: Math.floor((Math.random()*100)+1) });
        }, 500);

      } else {

        // We're done -- inform our caller 
        defer.resolve(results);
      }

      // Return the promise which we will resolve when we're done
      return defer.promise;
    },
  };

});
.

このプランカー

他のヒント

以下のアプローチを使用してみてください:

var idsArray= [], result = [];

/// ...After filling array

function nextIteration(index) {
   MyService.fetch(idsArray[index]).success(function (data, status, headers, config)
   {
      result.push(data);
      if (++index < idsArray.length) {
         nextIteration(index)
      } else {
         console.log('Task complete');
      }
}

nextIteration(0);
.

$qall()メソッドを使用して、定義したすべての約束をバンドルしてから、 All が解決された後の何かを解決します。

$q.all([promise1, promise2, ...]).then(...)
.

コントローラまたはサービス内のこの機能を実装することを検討してください。

は、完全なAPIリファレンスと詳細についてを参照してください。

更新

あなたのサービスがIDの配列を受け入れることができ、それがあなたが望む順序でデータを再帰的に取得するメソッドを持つことができます。外観と次のコード、それはそのままではないかもしれません:

function(){
    var result = [];
    var fetch = function(idArr /*this is your ID array*/){

          (a simple guess if what you want to do with that ID)
          $http.get('yourURL?id=' + <first element of idArr>)
            .success(function(data){
                //some logic
                result.push(data);
                idArr.splice(1,0);
                fetch(idArr);
            });
    }
}
.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top