从Rails到Angularjs的JSON

0 javascript json ruby-on-rails heroku angularjs

我正在尝试使用Angularjs从我放在Heroku上的Rails测试应用程序中获取JSON.您将在下面找到我的Angular和Rails代码.

这是我在Firebug控制台中遇到的错误."NetworkError:404 Not Found - http://desolate-earth-2852.herokuapp.com/declarations.json "

这有什么原因不起作用吗?

Angularjs代码

var App = angular.module('App', []);

App.controller('TodoCtrl', function($scope, $http) {
  $http.get('http://desolate-earth-2852.herokuapp.com/declarations.json')
       .then(function(res){
          $scope.todos = res.data;        
        });
});
Run Code Online (Sandbox Code Playgroud)

Rails代码

  def index
    @declarations = Declaration.all

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @declarations }
    end
  end
Run Code Online (Sandbox Code Playgroud)

这是路线

Test::Application.routes.draw do
  root :to => 'welcome#index'
  get "welcome/index"
  resources :declarations
end
Run Code Online (Sandbox Code Playgroud)

jjl*_*jl2 5

这可能是因为Rails JS缩小了.Ryan Bates在他的Railscast中谈到了关于整合AngularJS的问题.我注意到你没有提到你在配置文件中考虑了缩小,如果不是,那么这意味着你的Angular代码中的所有依赖注入都需要放入和数组中,如下所示:

App.controller('TodoCtrl', ['$scope', '$http', function($scope, $http) {
  $http.get('http://desolate-earth-2852.herokuapp.com/declarations.json')
    .then(function(res){
       $scope.todos = res.data;        
    });
}]);
Run Code Online (Sandbox Code Playgroud)

而不是这个:

App.controller('TodoCtrl', function($scope, $http) {
  $http.get('http://desolate-earth-2852.herokuapp.com/declarations.json')
   .then(function(res){
      $scope.todos = res.data;        
   });
});
Run Code Online (Sandbox Code Playgroud)

这告诉AngularJS依赖是什么,这样如果名称确实发生了变化(在缩小期间),那就不重要了.您必须为接受服务的每个功能执行此操作,例如您在此处创建应用程序控制器的功能.