Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm having trouble using a Rails JSON API in my angular app. I created a service in Angular that does this is querying my rails database for the index with code like this:

var app = angular.module('myApp');

app.factory('Comment', function($resource) {
    return $resource('http://localhost:3000/comments.json', {},{
      index: { method: 'GET', isArray: true, responseType: 'json' },
      show: { method: 'GET', responseType: 'json' },
      update: { method: 'PUT', responseType: 'json' }
    });
  });


app.controller('MainCtrl', function ($scope, Comment) {
    $scope.json = Comment.index();
  });

My Rails controller code looks like this:

  def index
    @comments = Comment.all

    render json: @comments
  end

My routes file is just:

resources :comments

And I know that my Angular App is pinging my rails API for the information because when I start the server my rails console says:

Started GET "/comments.json" for 127.0.0.1 at 2014-05-29 20:36:16 -0700
Processing by CommentsController#index as JSON
Comment Load (0.2ms)  SELECT "comments".* FROM "comments"
Completed 200 OK in 2ms (Views: 2.1ms | ActiveRecord: 0.2ms)

But it just returns an empty array when I bind $scope.json in my HTML file.

share|improve this question
1  
Change your url to "/comments" instead of "/comments.json". Your rails app is responding to "/comments" directly. You can also check the browser by going to "/comments" and "/comments.json" and see what they return. –  Ace Dimasuhid May 30 at 4:05
    
Agree with above statements, use POSTMan or curl or Firebug or the network panel in the browser (F12) to debug network requests to understand the results in a raw format and to be able to "test" your service layer separately. –  shaunhusain May 30 at 4:24
    
I actually resolved this issue myself. I changed my routes file to put the resources under the :api namespace. I had tried that before, but then I made my controller class part of the Api module and physically moved the controller file into an api folder under my controller folder. This finally properly exposed my json output to my angular controller. Thanks for your guyses responses. –  user3321729 May 30 at 17:53

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.