简体   繁体   English

如何访问返回的json对象的属性? (AngularJS)

[英]How to access the properties of returned json object? (AngularJS)

I'm trying to do an api call to facebook (using angularJs. Here's my code (taken from the service): 我正在尝试对facebook进行api调用(使用angularJs。这是我的代码(取自服务):

fbTest: function (name) {
    resource = $resource('http://graph.facebook.com/:id?fields=id,name,picture', { id: '@id' });
    return resource.get({ id: name });
}

It returns the data just fine: (inspected with Fiddler) 它返回数据就好了:(用Fiddler检查)

HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Cache-Control: private, no-cache, no-store, must-revalidate
Content-Type: application/json; charset=UTF-8
ETag: "c49e5dcad5a864ff2e16bb3af547231f725c05e7"
Expires: Sat, 01 Jan 2000 00:00:00 GMT
Pragma: no-cache
X-FB-Rev: 1002313
X-FB-Debug: tMeW4nnfiRBj6VK+QRtbe0YdaGfQfkXcaWL4VzXTXxw=
Date: Mon, 11 Nov 2013 16:53:29 GMT
Connection: keep-alive
Content-Length: 241

{
   "id": "Data",
   "name": "Data",
   "picture": {
      "data": {
         "url": "Data",
         "is_silhouette": false
      }
   }
}

However how can I access the properties? 但是,我如何访问属性? I tried writing .name but that doesn't return anything. 我尝试写.name,但不会返回任何内容。

The documentation is a little unclear to me, but it seems like some of the exposed methods such as .get execute asynchronously. 文档对我来说有点不清楚,但似乎有一些公开的方法,如.get异步执行。 What this means is that the return value from .get may not actually be returning the data from HTTP. 这意味着.get的返回值实际上可能不会从HTTP返回数据。

Instead, you need to do something like: 相反,你需要做类似的事情:

resource.get({ id: name }, function (data) {
    // do something with data.name, etc.
});

It happens because the result of the get isn't ready when you return the function. 发生这种情况是因为返回函数时get的结果尚未就绪。 You are returning a promise . 你回来了一个promise

Try binding the $resource.get to some attribute in your $scope and, when ready, it will be displayed correctly. 尝试将$resource.get绑定到$scope某个属性,并在准备好后将正确显示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM