Angularjs:我想将响应对象的结果打印到$ http get response中的各个元素中。请参阅下面的代码

时间:2017-02-14 08:43:29

标签: angularjs json http get

这是json:

 {"item":{"id":"3","firstName":"Eugene","lastName":"Lee","managerId":"1","title":"CFO","department":"Accounting","city":"Boston, MA","officePhone":"617-000-0003","cellPhone":"781-000-0003","email":"elee@fakemail.com","picture":"eugene_lee.jpg","managerFirstName":"James","managerLastName":"King","reportCount":"0"}}

现在有了$ http获取请求,我试图将响应作为

{"id":"3","firstName":"Eugene","lastName":"Lee","managerId":"1","title":"CFO","department":"Accounting","city":"Boston, MA","officePhone":"617-000-0003","cellPhone":"781-000-0003","email":"elee@fakemail.com","picture":"eugene_lee.jpg","managerFirstName":"James","managerLastName":"King","reportCount":"0"} 

使用以下代码

.controller('Detailing', function($scope, $http, $stateParams) {
$http.get("//localhost/directory/services/getemployee.php?id="+$stateParams.id)
.then(function(response) {
    $scope.employee = response.data.item;
})
});

它给了我未定义的。

2 个答案:

答案 0 :(得分:0)

.controller('Detailing', function($scope, $http, $stateParams) {
 $http.get("//localhost/directory/services/getemployee.php?id="+$stateParams.id)
.then(function(response) {
   $scope.employee = response.data; // Without item key
 })
});

JSON不包含item密钥。因此给出了这个错误。试试上面的

答案 1 :(得分:0)

一些观察结果:

  • 您的回复是JSON string而不是JSON object。因此,当您尝试从JSON string获取项目对象时,它会为您提供undefined

enter image description here

  • 您从$http.get请求获得的回复中没有项目对象。

enter image description here

解决方案:

如果您获得的回复是JSON.parse(),请使用JSON string将JSON字符串转换为JSON对象。

<强>样本

&#13;
&#13;
var obj = '{"item":{"id":"3","firstName":"Eugene","lastName":"Lee","managerId":"1","title":"CFO","department":"Accounting","city":"Boston, MA","officePhone":"617-000-0003","cellPhone":"781-000-0003","email":"elee@fakemail.com","picture":"eugene_lee.jpg","managerFirstName":"James","managerLastName":"King","reportCount":"0"}}';

var data = JSON.parse(obj);
console.log(data.item);
&#13;
&#13;
&#13;