0

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.

2
  • 2
    try console.log(JSON.stringify(object)). Commented Jul 15, 2014 at 4:04
  • Ok, I did that. Here was my response: {"$promise":{},"$resolved":false} I don't know about promises so I don't have the faintest idea how to handle that or if I need to use a promise. Any ideas? Commented Jul 15, 2014 at 4:20

3 Answers 3

1

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;
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the help. I used this code and started seeing this error Error: 'undefined' is not a function (evaluating 'nprService.get().then(function(result){ $scope.article = result.data; })') I looked into it but can't figure out how I might fix it. Thanks.
0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.