【问题标题】:Using $resource.query on an array of objects在对象数组上使用 $resource.query
【发布时间】:2015-06-13 04:41:34
【问题描述】:

json

[ { "id":"0", "name" : "BCAA & GLUTAMINE", "brand" : "NRG FUEL", "price": "20", "description": "NRGFUEL 100% BCAA & Glutamine powder has been scientifically formulated to promote full muscle recovery, growth and repair whilst preventing muscle breakdown. Consisting of our instantized BCAA (2:1:1 RATIO) and absolute pure glutamine NRGFUEL’S BCAA and Glutamine powder will keep you in a positive state of growth and recovery. If you train hard, you need to recover hard.", "img" : "images/products/dietforcewhey.jpg" }, { "id":"1", "name" : "WHEY PLUS RIPPEDCORE", "brand" : "SCISMX NUTRITION", "price": "20", "description": "NRGFUEL 100% BCAA & Glutamine powder has been scientifically formulated to promote full muscle recovery, growth and repair whilst preventing muscle breakdown. Consisting of our instantized BCAA (2:1:1 RATIO) and absolute pure glutamine NRGFUEL’S BCAA and Glutamine powder will keep you in a positive state of growth and recovery. If you train hard, you need to recover hard.", "img" : "images/products/wheyplusrippedcore.jpg" } ]

控制器

app.controller('productDetails', ['$scope', '$routeParams', 'productService', function ($scope, $routeParams, productService) {
$scope.products = productService.query();
$scope.product = $scope.products[$routeParams.id];


console.log($scope.product)

}]);

服务

app.factory('productService', ['$resource', function ($resource) {
return $resource('json/products.json'); 

}]);

当我 console.log $scope.product 我得到“未定义”但 scope.products 工作正常。

有人可以解释一下我做错了什么吗?

【问题讨论】:

    标签: angularjs ngresource


    【解决方案1】:

    啊,这一直是我在使用 $resource 时最头疼的问题之一!

    问题在于 $scope.products = productService.query();是异步的。这意味着 $scope.product 将被设置为尚不存在的东西。也就是说,代码直接跳过 .query() 到该行。

    您需要做的是将该语句放在异步函数的回调中,以便它在完成时运行。像这样:

    $scope.products = productService.query(function(result){
      $scope.product = result[$routeParams.id];
    });
    

    希望对您有所帮助! :)

    【讨论】:

    • 哇,这么近却又这么远。我真的很感激!谢谢你!
    猜你喜欢
    • 1970-01-01
    • 2018-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-10
    • 2019-07-23
    • 2019-10-02
    • 2021-03-13
    相关资源
    最近更新 更多