web-dev-qa-db-ja.com

angular.forEachとオブジェクト

問題:

私は、配列に対して単純なangular.forEachを実行し(そうではないかもしれませんが)、$resourceを使用して、返される各値に基づいて呼び出しを行います。私が期待しているように、各呼び出しの結果はオブジェクトです。しかし、これらのオブジェクトを angular.forEach documentation が示す方法で調和して結合させることはできません。

しかし、最初に動作するコードと、失敗するコードを見てみましょう。

作品

var uniqueIds = {};
angular.forEach(object, function(key, value){
    this.Push(key.uniqueIds);
}, uniqueIds);
console.log(uniqueIds)
// uniqueIds equals the expected array

失敗

ここで注意が必要な箇所があります。さて、次のサンプルでは、​​angular.forEachの中に$resource呼び出しがあります。

angular.forEach(array, function(index){
    Resource.query({id:index}, function(result){
        console.log(result)
        // returns the expected object, 
        // but, as expected, I can't access the object outside the async call
    });
    console.log(result);
    // result is undefined
 });

非同期性を考えると、問題を解決できる見込みがあるようです。しかし、そうではありません-私はまだ非同期呼び出しの中にいます。 result$scopeに割り当てることもできません。要するに、Resource.query以外の値を取得することはできないようです。

何をする必要がありますか?

$resourceが配列を作成したのと同じ方法で、(angular.extendを使用して?)を1つのオブジェクトに追加するには、各angular.forEach呼び出しの返されたオブジェクトが必要です。私は多くの異なるアプローチを試しましたが、そのほとんどはここで尋ねられた一般的な非同期の質問に対する答えに基づいていますが、今のところ何の役にも立ちません。 $resource呼び出しから値を取得することには問題があると確信していますが、この場合の方法は少し困惑しています。

13
jody tate

このようなもの?

var promises = [];

angular.forEach(array, function(index) {
  promises.Push(Resource.query(...));
});

$q.all(promises).then(function(result1, result2, result3 ...) {
  // do stuff with result1, result2 ... or
  // var results = Array.prototype.slice.call(arguments);
});
17

Angular documentation これには非常に良い例があります

var values = {name: 'misko', gender: 'male'};
var log = [];
angular.forEach(values, function(value, key) {
    this.Push(key + ': ' + value);
 }, log);
4
Yasser

.queryは、xhrが完了したときにデータで満たされている配列参照を返します。おそらくidは一意の識別子であるため、クエリは単一の要素を持つ配列を返します。そのため、代わりに.getを使用することをお勧めします。

とにかく、.queryを使用したい場合は、次のようなことができます。

var arrays = [];
angular.forEach(array, function(index){
    arrays.Push(Resource.query({id:index}, function(result){
        console.log(result)
        // returns the expected object, 
        // but, as expected, I can't access the object outside the async call
    }));
    console.log(result);
    // result is undefined
});

$scope.$watch(function () {
    return arrays;
}, function (arrays) {
    angular.forEach(arrays, function (array) {
       angular.forEach(array[0], function () {
          //Do something with the object fields
       });
    });
});

あなたが見ることができるように、コードはかなり悪く見えます...

より良い結果を得るには、次を使用できます。

var objects = [];
angular.forEach(array, function(index){
    objects.Push(Resource.get({ id:index });
});

$scope.$watch(function () {
    return objects;
}, function (objects) {
    angular.forEach(objects, function (obj) {
       angular.forEach(obj, function () {
          //Do something with the object fields
       });
    });
});

objects$watchプロパティに割り当てることで、AngularJSに$scopeを実行させるとさらに良いでしょう。

2
Minko Gechev