Javascript 如何使用angularJS中的$resource从json检索值

Javascript 如何使用angularJS中的$resource从json检索值,javascript,angularjs,Javascript,Angularjs,如何使用$resource从调用中检索值,并在JS中使用它,而不是仅在具有数据绑定的视图中使用它 我有一个JSON: { "id": 18, "name": "adsfadsf", "type_of_dish": "Tacos", "cost": "5.95", "notes": "bla bla bla", "totalrecipes": 1, "dish_recipes_attributes": [ {

如何使用$resource从调用中检索值,并在JS中使用它,而不是仅在具有数据绑定的视图中使用它

我有一个JSON:

{
    "id": 18,
    "name": "adsfadsf",
    "type_of_dish": "Tacos",
    "cost": "5.95",
    "notes": "bla bla bla",
    "totalrecipes": 1,
    "dish_recipes_attributes": [
        {
            "recipe_id": 28,
            "no_recipe": 1,
            "name": "tacos al pastor piña",
            "cost_portion": "5.95"
        }
    ]
}
在我的JS中:

$scope.dish = Dish.get({id: $routeParams.id});
我需要得到“totalrecipes”的值,我尝试过这个,但没有成功:

var totalrecipes = $scope.dish.totalrecipes;
console.log(totalrecipes);  //Undefined
console.log($scope.dish); // [object Object]
但在我看来,一切都很好:

{{dish.totalrecipes}}   // 1, It's OK!

请记住,资源的操作函数是异步的,只返回承诺对象。你可以在报纸和文档中读到这一点。视图实际上是为了在承诺“实现”后更新自身而设计的,这就是为什么值会显示在视图中

考虑以下示例:

$scope.dish = Dish.get({id: 123})
alert($scope.dish.totalrecipes);
在这种情况下,
$scope.dish
将被分配一个promise对象,直到加载实际值为止(这可能发生在以后的任何时间点,或者根本不发生)

相反,您可以使用回调方法,或者直接作为
get
函数的参数,或者使用promise API:

或者:

$scope.dish = Dish.get({id: 123})
$scope.dish.$promise.then(function(dish) {
    alert(dish.totalrecipes);
});

请记住,资源的操作函数是异步的,只返回承诺对象。你可以在报纸和文档中读到这一点。视图实际上是为了在承诺“实现”后更新自身而设计的,这就是为什么值会显示在视图中

考虑以下示例:

$scope.dish = Dish.get({id: 123})
alert($scope.dish.totalrecipes);
在这种情况下,
$scope.dish
将被分配一个promise对象,直到加载实际值为止(这可能发生在以后的任何时间点,或者根本不发生)

相反,您可以使用回调方法,或者直接作为
get
函数的参数,或者使用promise API:

或者:

$scope.dish = Dish.get({id: 123})
$scope.dish.$promise.then(function(dish) {
    alert(dish.totalrecipes);
});

“IsraelBarba,如果它完全回答了你的问题,也请考虑接受这个答案。”如果完全回答了你的问题,请考虑接受这个答案。