camlewis
camlewis

Reputation: 55

AngularJS - API call returning [object object]

I'm trying to call a list of articles from the NPR API. I have a working URL which returns as JSON. However, somewhere in my controller, I'm getting lost getting the object. When I console.log it to test, it returns as [object Object] and nothing else. My service looks like this:

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

and my controller:

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

I've tried using query to get the result, like this, but it's returning a single JSON object so that obviously didn't work.

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

Any help would be greatly appreciated. Thanks in advance.

Upvotes: 0

Views: 1460

Answers (3)

Rizwan
Rizwan

Reputation: 4463

Using Angular 6 you can try this

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

Upvotes: 0

bentesha
bentesha

Reputation: 948

The $resource.get() function returns a promise. It should be used this way:

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

Upvotes: 0

rchawdry
rchawdry

Reputation: 1266

You need to use a promise construct to get at the data. The controller code can be re-written as:

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

Upvotes: 1

Related Questions