【问题标题】:How to create a custom Serializer for Ember data如何为 Ember 数据创建自定义序列化程序
【发布时间】:2012-12-27 08:44:31
【问题描述】:

我有一个 API,它返回的 JSON 格式不适合 Ember 的使用。 取而代之的是(ember 所期待的):

{ events: [
    { id: 1, title: "Event 1", description: "Learn Ember" },
    { id: 2, title: "Event 2", description: "Learn Ember 2" }
]}

我明白了:

{ events: [
    { event: { id: 1, "Event 1", description: "Learn Ember" }},
    { event: { id: 2, "Event 2", description: "Learn Ember 2" }}
]}

所以如果我理解正确的话,我需要创建一个自定义的 Serializer 来修改 JSON。

var store = DS.Store.create({
    adapter: DS.RESTAdapter.create({
        serializer: DS.Serializer.create({
            // which hook should I override??
        })
    })
});

我已经阅读了DS.Serializer相关的代码注释,但是我无法理解如何实现我想要的......

我该怎么做?

ps:我的目标是让App.Event.find() 工作。目前,我收到Uncaught Error: assertion failed: Your server returned a hash with the key 0 but you have no mapping for it。这就是为什么我需要修复收到的 JSON。

编辑:我现在是这样工作的:

extractMany: function(loader, json, type, records) {
    var root = this.rootForType(type),
    roots = this.pluralize(root);

    json = reformatJSON(root, roots, json);
    this._super(loader, json, type, records);
  }

【问题讨论】:

  • 您在这里使用的是什么版本的 Ember Data?
  • CURRENT_API_REVISION: 4,如果有帮助的话...
  • FWIW,这是 Ember Data 的一个非常老旧过时的版本。

标签: javascript ember.js ember-data


【解决方案1】:

我假设响应仅包含 ID,并且您正在尝试提取它们。

您将希望继承 DS.JSONSerializer,它提供了处理 JSON 有效负载的基本行为。特别是,您需要覆盖 extractHasMany 挂钩:

// elsewhere in your file
function singularize(key) {
  // remove the trailing `s`. You might want to store a hash of
  // plural->singular if you deal with names that don't follow
  // this pattern
  return key.substr(0, key.length - 1);
}

DS.JSONSerializer.extend({
  extractHasMany: function(type, hash, key) {
    return hash[key][singularize(key)].id;
  }
})

【讨论】:

  • 谢谢!我已经用其他信息更新了我的帖子。 extractHasMany 永远不会被调用,extractMany 会被调用。我的目标只是让App.Event.find() 立即工作。我设法通过覆盖 extractMany 并手动修改 json 使其符合要求 ({ events: [ {}, {} ] })...
  • 我假设你在修改数据后打电话给this._super
  • 确实如此。我更新了我的答案。但我想知道是否没有更好的方法来做到这一点。现在可以了,如果我意识到我必须重写太多方法,那么我可以考虑改进它。谢谢。
猜你喜欢
  • 1970-01-01
  • 2019-11-27
  • 2017-03-02
  • 2021-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-05
相关资源
最近更新 更多