0

我正在尝试使用 ember-data 配置 ember 应用程序以连接并从一个 api 读取数据。我的模型是:

App.Movie = DS.Model.extend
  title: DS.attr 'string'
  rating_average: DS.attr 'string'
  short_plot: DS.attr 'string'
  free: DS.attr 'boolean'

我的 api 返回:

{
"pagination": {
    "count":xx,
    "page": x,
    "total_pages": x
},
"movies": [
    {
        "id": xxxx,
        "title": "xxx",
        "rating_average": "x",
        "short_plot": "xxxx",
        "already_seen": x,
 ....
 ....

当 ember 尝试加载数据时,它会抛出:

Assertion failed: Your server returned a hash with the key **pagination** but you have no mapping for it 

Ember 不期望 Json 中的“分页”键。如何指定仅尝试从键“电影”中读取?

4

1 回答 1

1

While it is possible to customize ember-data to handle this, consider using ember-model instead. ember-data works best when you have control over your API and can ensure that it follows a set of conventions. If that is not the case you will find yourself fighting to make ember-data work with your API and it was simply not designed for this use case. ember-model was designed for this use case and while it does less for you out-of-box it will be much easier to customize. See ember-model-introduction to learn more.

That said, to make things work with ember-data you'll need to extend the rest adapter and customize it's ajax function.

App.Store = DS.Store.extend({
  adapter: 'App.Adapter'
});
App.Adapter = DS.RESTAdapter.extend({
  ajax: function(url, type, hash) {
    var promise = this._super(url, type, hash);
    return promise.then(function(json) {
      delete json.pagination;
      return json;
    });
  }
});

In this custom adapter we are calling the rest adapter's ajax function - see source - which returns a promise. The promise's then() function can be used to strip the key pagination from the result. Of course that means the pagination key will be removed from every json response.

于 2013-08-30T15:52:30.663 回答