2014-07-15 143 views
0

我想调用NPR API中的文章列表。我有一个工作网址,它返回为JSON。然而,在我的控制器的某个地方,我迷路了。当我console.log它测试,它返回作为[对象对象],没有别的。我的服务是这样的:AngularJS - API调用返回[对象对象]

app.factory('nprService', function($resource) { 
//call npr api 
return $resource('http://api.npr.org/queryid=61&fields=title,byline,text,image,all&output=JSON... 

和我的控制器:

app.controller('ArticleListCtrl', function($scope, nprService) { 
//call the service and store as a variable 
$scope.article = nprService.get(); 
}); 

我一直在使用查询得到的结果,这样的尝试,但它返回一个JSON对象,这样显然没”工作。

//call the service and store as a variable 
nprService.query(function(data) { 
    $scope.article = data; 
}); 

任何帮助将不胜感激。提前致谢。

+2

尝试'console.log(JSON.stringify(object))'。 – Mritunjay

+0

好的,我做到了。这是我的回应:{“$ promise”:{},“$ resolved”:false}我不知道承诺,所以我没有最简单的想法如何处理,或者如果我需要使用承诺。有任何想法吗? – camlewis

回答

1

您需要使用promise构造来获取数据。控制器代码可以重写为:

app.controller('ArticleListCtrl', function($scope, nprService) { 
//call the service and store as a variable 
nprService.get().then(function(result){ 
    $scope.article = result.data; 
}); 
+0

感谢您的帮助。我使用这段代码并开始看到这个错误错误:'undefined'不是函数(评估'nprService.get()。then(function(result){scope =看着它,但无法弄清楚我会如何解决它。谢谢。 – camlewis

0

$ resource.get()函数返回一个承诺。它应该这样使用:

nprService.get().success(function(data, status, headers, config){ 
    $scope.article = data; 
}).error(function(data, status, headers, config){ 
    console.log(status); 
});