【问题标题】:JSON from Rails to Angularjs从 Rails 到 Angularjs 的 JSON
【发布时间】:2013-10-25 04:54:18
【问题描述】:

我正在尝试使用 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;        
        });
});

导轨代码

  def index
    @declarations = Declaration.all

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @declarations }
    end
  end

这里是路线

Test::Application.routes.draw do
  root :to => 'welcome#index'
  get "welcome/index"
  resources :declarations
end

【问题讨论】:

  • 你有这样定义的路由吗:resources :declarations
  • 是的,发布你的 routes.rb 代码
  • 我已经添加了路线。我已经有了资源:声明。
  • 奇怪的是你得到了 404。你是否也从同一个 herokuapp 运行角度代码?你能指定 Angular 代码运行的 url 吗?
  • @Manuel van Rijn。我在我的桌面上本地运行 Angular 代码

标签: javascript ruby-on-rails json angularjs heroku


【解决方案1】:

这可能是因为 Rails JS 缩小。 Ryan Bates 在他的Railscast about integrating 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;        
    });
}]);

而不是这个:

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

这告诉 AngularJS 依赖项是什么,因此如果名称确实发生了变化(在缩小期间),则无关紧要。您必须为每个接受服务的函数执行此操作,例如您在此处创建应用程序控制器的函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-29
    • 1970-01-01
    相关资源
    最近更新 更多