Emberjs 没有将 JSON 转换为模型数组

Emberjs not converting JSON to model array

我正在从我的 Emberjs 向我的 Rails 服务器上的 explore 路由发出自定义请求:

GET http://localhost:3000/explore

我在 Google Chrome 网络检查器中看到了我的 JSON 响应,但是,我的页面没有呈现任何内容。

要发出自定义请求,我有一个 book 适配器:

书籍适配器

import ApplicationAdapter from './application';
import Ember from 'ember';

export default ApplicationAdapter.extend({
  apiManager: Ember.inject.service(),

  findPublishedBooks: function(store, type) {
    let jwt = this.get('apiManager').get('jwt');

    return Ember.RSVP.resolve(
      Ember.$.ajax({
        type: "GET",
        url: this.get('apiManager').requestURL('explore'),
        dataType: 'json',
        headers: {"Authorization": "Bearer " + jwt}
      })
    );
  }
});

探索路线

model() {
  const adapter = this.get('store').adapterFor('book');
  return adapter.findPublishedBooks();
}

在我的Rails这边,我有这个用于我的探索操作:

Rails探索行动

def explore
  books = Book.where(published: true)

  if books.count > 0
    render json: books
  else
    return nil
  end
end

我知道我一定是做错了什么,可能是在我Ember这边。

更新

探索模板

<div class="explore">
  {{#search-field searchAction=(action "searchBooks") clearAction=(action "clearSearchBooks")}}{{/search-field}}
  {{#book-grid books=model class="book-grid" isSearching=isSearching}}{{/book-grid}}
</div>

书籍网格模板

{{#each books as |book|}}
  {{#link-to "books.book" book}}
    <div class="book">
      <div class="book-cover">
        <img src={{book.cover.cover.url}} alt="{{book.title}} book cover image" width=173 height=231>
      </div>
      <div class="caption">
        {{book.title}}<br>
        <label>by {{book.author.username}}</label>
      </div>
    </div>
  {{/link-to}}
{{else}}
  {{#if isSearching}}
    <label>No search results.</label>
  {{else}}
    <label>There are no published books at the moment.</label>
  {{/if}}
{{/each}}

我认为您需要了解您的代码基本上是围绕 ember-data 商店工作的。要使 ember-data 正常工作,您必须将所有数据保存在存储中,这意味着您不能仅手动调用适配器。你总是要打电话给商店,商店会打电话给适配器。

所以这是一个反模式:

const adapter = this.get('store').adapterFor('book');
return adapter.findPublishedBooks();

因为它不会将数据推送到存储中,也不会序列化它们。

您应该做的是在商店中使用 query 功能。

如果您需要服务器端过滤列表,您可以调用 store.query('myModel', anything)。第二个变量将直接传递给适配器。

所以你会在你的路线中调用 return store.query('book', { published:true }),然后在你的 BookAdapter 中用这样的东西实现它:

apiManager: Ember.inject.service(),

query: function(store, type, query) {
  if(query.published) {
    let jwt = this.get('apiManager').get('jwt');

    return Ember.RSVP.resolve(
      Ember.$.ajax({
        type: "GET",
        url: this.get('apiManager').requestURL('explore'),
        dataType: 'json',
        headers: {"Authorization": "Bearer " + jwt}
      })
    );
  }
}

还要确保 return 正确的数据结构。 ember-data 期望 JSONAPI 响应,除非您在序列化程序中更改了它。