【问题标题】:Retrieve Rails Records Using Angular $resource使用 Angular $resource 检索 Rails 记录
【发布时间】:2015-04-03 00:55:24
【问题描述】:

我正在尝试使用 Angular 的 $resource 检索 Rails 记录的集合,但是当我尝试在视图中呈现这些记录时,我不断得到一个空数组。

posts_controller.rb

def index
  @posts = current_user.author.posts.limit(25)
end

app.js.coffee

app = angular.module('app', ['ngResource'])

app.factory 'Posts', ($resource) ->
  $resource '/posts/:id', {}, query:
    method: 'GET'
    isArray: true
    responseType: 'json'

app.controller 'PostsCtrl', ($scope, Posts) ->
  $scope.posts = Posts.query()

在控制台中,我看到 $resolved 是错误的,所以我不确定问题是否与访问 json 数据本身或 $promise 有关

【问题讨论】:

    标签: ruby-on-rails angularjs angular-resource


    【解决方案1】:

    您需要花点时间了解异步编程,因为它来自像 Ruby 这样缺乏异步的语言。

    您需要将回调传递给 query() 方法。所以你的例子应该看起来像(在 JS 中):

    Posts.query(function(posts) {
        $scope.posts = posts;
    })
    

    附带说明:最好在 JavaScript 中发布示例 Angular 代码——除非问题是针对 CoffeeScript 的。

    【讨论】:

    • 知道了。 $resolved 现在为真,但仍返回一个空数组。所以看起来根本问题是 $resource 没有正确访问我的 rails 记录。解决此问题的最佳方法是什么?
    • 使用浏览器中的开发者工具来确认你的假设。您应该能够看到请求和响应。在 Chrome 开发工具中转到网络,选择过滤器并选择 Ajax。
    • 是的,它开始工作了,我不得不改变我在 (rails) 控制器中获取记录的方式
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-16
    • 2016-10-02
    • 2017-01-13
    • 1970-01-01
    相关资源
    最近更新 更多