javascript - 无法访问返回的 JSON 对象的子对象

标签 javascript json angularjs

我可能只是盲目的或者什么的,但我真的不明白为什么我无法访问返回的 $Resource 对象的子对象,该对象检索了一堆 JSON 对象。

Resource
> $resolved: true
> $then: function (b, g) {var j=e(),h=
> data: Object
  > 519bc5f6b2427a732be1c360: Object

原始 JSON 如下所示:

{
    "data": {
        "519bc5f6b2427a732be1c360": {
            "id": "519bc5f6b2427a732be1c360",
            "planning": {
                "id": "519bc5f6b2427a732be1c355"
            }
        }
    }
}

谁能解释一下为什么这不起作用:

var training = Training.query()

console.log(training); // returns the entire $Resource
console.log(training.data); // returns: undefined 

最佳答案

这里是解释 - 来自 the Angular docs :

It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on isArray). Once the data is returned from the server the existing reference is populated with the actual data. This is a useful trick since usually the resource is assigned to a model which is then rendered by the view. Having an empty object results in no rendering, once the data arrives from the server then the object is populated with the data and the view automatically re-renders itself showing the new data. This means that in most case one never has to write a callback function for the action methods.

所以这有效:

var training = Training.query(function(value){
  // this is the callback function
  console.log(training === value); // true - it's the same object
  console.log(training.data); // and now it has data
});

关于javascript - 无法访问返回的 JSON 对象的子对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16749519/

相关文章:

javascript - 使用 mozilla Thunderbird 扩展更改文件夹名称

javascript - Android 的错误代码 : 500 on react native 0. 56

json - jq:如何并排获取 2 个一维数组作为输出

javascript - 使用 yyyy/mm/dd 格式以 ng-repeat 显示本周数据

angularjs - angular-ui-select 如何为选项创建自定义对象

javascript - 如何使用 JS 将时间设置为 T00 :00:00. 000Z

javascript - 单击复选框按钮时,禁用所有输入类型值

javascript - History.pushState 和遍历历史 - PhoneGap/Android

javascript - 如何使旋转元素高度为:100% of its parent?

json - "expand"/在 MSSQL 上通过 JSON 值加入 SQL 选择