2016-04-01 66 views
0

请查看我的代码。使用geofire和firebase循环访问数组时重复数据

var posts = PostsData.getPosts(); 
    var postFunc = function(key) { 
     return posts[key]; 
    } 

    $scope.$watch($scope.active, function() { 
     $timeout(function() { 
    var markers = []; 

    for (var key in posts) { 

      console.log(key); 
      var p = gf.get(key).then(function(location) { 
      var post = postFunc(key); 
      console.log(key); 
      return ({ 
      idKey: key, 
      title: post.title, 
      coords: { 
       latitude: location[0], 
       longitude: location[1] 
      } 
      }); 
     }); 
     markers.push(p); 

    } 

    $q.all(markers).then(function(markers) { 
    $scope.markers = markers; 
    }); 

    }); 
}) 

}

在循环内有两行 “的console.log(密钥)”。 第一个console.log输出唯一键的数据的准确表示。第二个console.log打印重复相同的数据,这是不准确的。我无法理解为什么会发生这种情况。

非常感谢您的帮助。

回答

0

这是很正常的,从第二console.log(key)以后你有相同的值。原因是你的异步功能gf.get(key).then(function(location) { .. }。在调用此函数时,您的循环已完成执行,并且key的值是循环的最后一个值。我不知道什么gf.get做,但如果posts是一个数组,你可以实现与递归的帮助,你的结果如下图所示

var posts = PostsData.getPosts(); 
var postFunc = function(key) { 
    return posts[key]; 
} 

var markers = []; 
var getMarkers(key) { 

    if (key > posts.length - 1) { 

     // promise resolved for each item in posts 
     $q.all(markers).then(function(markers) { 
      $scope.markers = markers; 
     } 

     return; 
    } 

    console.log(key); 
    gf.get(key).then(function(location) { 
     var post = postFunc(key); 
     console.log(key); 
     markers.push({ 
      idKey: key, 
      title: post.title, 
      coords: { 
       latitude: location[0], 
       longitude: location[1] 
      } 
     }); 

     getMarkers(++key); 
    }); 
} 

$scope.$watch($scope.active, function() { 
    markers = []; 
    getMarkers(0); 
}); 

注:在这个方法中,我们等待每一个承诺移动到前解决的gf.get

+0

非常感谢!我不得不做一些小的改变,但它的工作。 –

0

的另一种技术下一个呼叫以解决此问题是使用IIFE闭合。

var markers = []; 

for (var key in posts) { 
    //IIFE closure 
    (function (key) { 
     console.log(key); 
     var p = gf.get(key).then(function(location) { 
      var post = postFunc(key); 
      console.log(key); 
      return ({ 
       idKey: key, 
       title: post.title, 
       coords: { 
        latitude: location[0], 
        longitude: location[1] 
       } 
      }); 
     }); 
     markers.push(p); 
    })(key); 
} 

通过使用IIFE(Immediately Invoked Function Expression)每个key的值被保留,直到.then方法内的函数完成。