AngularJS - 来自$ resource的空数组的forEach()

时间:2016-12-22 20:23:25

标签: javascript angularjs arrays foreach

我有一个从服务获得的数组但在控制器中我在forEach()函数中得到一个空值。这是code

控制器

此处,'products'和'copyProducts'均为空。我需要将'copyProducts'数组用于forEach()函数。

app.controller("controllerApp", function($scope, serviceApp){

  var products = serviceApp.query(); 
  $scope.copyProducts = products;

  angular.forEach($scope.copyProducts, function(value, key){
    console.log("object: "+value);
  })

});

服务

app.factory("serviceApp", function($resource){
  return $resource("products.json", {}, {
        getAll: {
            method: "GET",
            isArray: true
        }
    })
})

1 个答案:

答案 0 :(得分:6)

您的代码错误,因为static const auto gAdjacentPred = []( const int& lhs, const int& rhs) { std::cout << "(" << lhs << ":" << rhs << ")?" << std::string((rhs == lhs+2)? "true" : "false") << std::endl; return (rhs == lhs+2); }; std::vector<int> myvector = { 1, 3, 3, 5, 7, 9, 13, 10, 12 }; auto adjIter = std::adjacent_find ( myvector.begin(), myvector.end(), gAdjacentPred); while (adjIter != myvector.cend()) { auto second = std::next(adjIter); // print both sides if (second != myvector.cend()) { std::cout << "{" << *adjIter << "," << *second << "}" << std::endl; adjIter +=2; } else { adjIter++; } } 是异步的,因此它不会立即完成,并且结果未在同一行的下一行准备就绪。因此,一旦完成它的工作,它就需要一个回调函数。

.query()

替代:

serviceApp.query().$promise.then(function(res) {
  $scope.products = res;
  $scope.copyProducts = res;
  angular.forEach($scope.copyProducts, function(item) {
    console.log(item)
  })
});

顺便说一下,如果您想使用资源中定义的serviceApp.query({}, function(res, headers){ //etc }); 方法,那么将使用query()

getAll