AngularJS - 返回[object object]的API调用

时间:2014-07-15 04:01:34

标签: javascript json angularjs

我试图从NPR API调用文章列表。我有一个返回JSON的工作URL。然而,在我的控制器的某个地方,我迷失了对象。当我在console.log中进行测试时,它返回[object Object]而没有别的。我的服务如下:

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;
});

非常感谢任何帮助。提前谢谢。

3 个答案:

答案 0 :(得分: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;
});

答案 1 :(得分:0)

$ resource.get()函数返回一个promise。它应该以这种方式使用:

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

答案 2 :(得分:0)

使用Angular 6你可以尝试这个

myFunctionName(){
this.http.get(`http://www.thesoftdesign.com`)
      .map(res => res.json())
      .subscribe(data => {
        this.data = data;
        console.log('data', this.data);
      });
}
相关问题