Ember.js改变RESTAdapter JSON序列化

Ember.js changing RESTAdapter JSON serialization

本文关键字:JSON 序列化 RESTAdapter 改变 js Ember      更新时间:2023-09-26

我有一个模型,我从一个API查询:

App.Deal = DS.Model.extend({
  name: DS.attr('string'),
  value_in_cents: DS.attr('number'),
  closed_time: DS.attr('date'),
  user: DS.attr('object'),
  company: DS.attr('object')
});

API返回如下内容:

{ 
  pagination: { page: 1, total: 10 },
  entries: [ deal1, deal2, deal3, deal4 ]
}

我已经更新了我的适配器如下:

App.Adapter = DS.RESTAdapter.extend({
  url: 'http://api.pipelinedeals.com/api/v3',
  serializer: DS.RESTSerializer.extend({
    extractMany: function(loader, json, type, records) {
      var root = this.rootForType(type);
      var roots = this.pluralize(root);
      formattedJson = {};
      formattedJson[roots] = json.entries;
      delete formattedJson.pagination;
      this._super(loader, formattedJson, type, records);
    }
  })
});

newJson有我想要的格式,但我得到以下错误:

Uncaught Error: assertion failed: You tried to use a attribute type (object) that has not been registered ember-1.0.0-rc.2.js:52

你想从DS.RESTSerializer继承和覆盖extractMany有这样的东西:

extractMany: function(loader, json, type, records) {
    var root = 'entries';
    if (json[root]) {
      var objects = json[root], references = [];
      if (records) { records = records.toArray(); }
      for (var i = 0; i < objects.length; i++) {
        if (records) { loader.updateId(records[i], objects[i]); }
        var reference = this.extractRecordRepresentation(loader, type, objects[i]);
        references.push(reference);
      }
      loader.populateArray(references);
    }
  },

由于您的服务器没有将类型设置为根,因此您将无法使用侧加载