sir_thursday
sir_thursday

Reputation: 5419

Angular resource call returning no error/data

Here's my controller call to the service:

  Answers.getAnswers($routeParams.questionId, function(answers) {
    console.log(answers);
    $scope.answers = answers;
  });

Here's the service:

angular.module('intquestApp')
  .factory('Answers', function ($resource) {
    return {
        getAnswers: function(questionId) {
          $resource('api/answers?questionid=' + questionId);
        }
    };
  });

I can confirm the resource is there for certain, and I know that the value of questionId is accurate. Am I doing something syntactically wrong?

Upvotes: 1

Views: 86

Answers (2)

V31
V31

Reputation: 7666

From the looks of your controller code it appears that you require a callback in the factory. Here is the factory code (you had it wrong syntactically)

Factory Code:

//Define a module like this
angular.module('intquestApp',[])
  .factory('Answers', function ($resource) {
    return {
        getAnswers: function(questionId,callback) {
          //define resource
          var questionURL = $resource('api/answers?questionid=' + questionId);
          //fire the get call
          questionURL.get().$promise.then(function(answer){
             //return answer in callback
             callback(answer);
          });
        }
    };
  });

Controller Code:

 Answers.getAnswers($routeParams.questionId, function(answers) {
    console.log(answers);
    $scope.answers = answers;
  });

Upvotes: 1

Cyril Duchon-Doris
Cyril Duchon-Doris

Reputation: 14039

From angularJS doc :

It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on isArray).

What you want to use is a promise like explained there

Answers.getAnswers($routeParams.questionId).$promise.then(function (result) {
   $scope.answers = result;
})

Upvotes: 1

Related Questions