我正在尝试使用 ng-resource 来显示书名索引。这是 AngulaRails 的第 11 章,到目前为止真的很难。
我知道我的问题与尝试在我的咖啡脚本控制器中使用资源有关,因为当我只使用带有特定 url 的 $http“get”请求时,一切正常。这是我的代码的所有部分:
1.javscripts/application.js
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require bootstrap.min
//= require angular.min
//= require angular-resource
//= require angular-application
2 串行器:
class BookSerializer < ActiveModel::Serializer
attributes :id, :title, :author
end
3 这工作正常:
AngulaRails.config ["$httpProvider", ($httpProvider) ->
$httpProvider.defaults.headers.common['X-CSRF-Token'] = $('meta[name=csrf-token]').attr('content')
$httpProvider.defaults.headers.common.Accept = "application/json"
]
4 javascripts/angular-application.js
//= require_self
//= require_tree ./angular
AngulaRails = angular.module("AngulaRails", ["ngResource"]);
5 我要查看的索引的索引控制器:
# GET /books
def index
@books = Book.all
respond_to do |format|
format.html { }
format.json { render json: @books, root: false, each_serializer: BookSerializer }
end
end
6 我尝试使用的资源的工厂。在这种情况下,我调用索引的查询:
AngulaRails.factory "Book", ($resource) ->
$resource("/books/:id")
{
'get': {method: 'GET'},
'save': {method: 'POST'},
'query': {method: 'GET', isArray: true},
'remove': {method: 'DELETE'},
'delete': {method: 'DELETE'}
}
7 最后但并非最不重要的是,此应用程序的咖啡脚本控制器:
AngulaRails.controller "BooksController", ($scope, Book) ->
$scope.getBooks = () ->
$scope.books = Book.query()
当我尝试运行它时,console.log 会给我一个错误说:
错误:Book.query 不是函数