【问题标题】:ember data serializer data mappingember 数据序列化器数据映射
【发布时间】:2013-04-08 20:46:40
【问题描述】:

我正在使用 ember 和 ember-data 来尝试使用来自服务器的 json 提要。这是我的代码:

App = Ember.Application.create();

DS.RESTAdapter.configure(
    "plurals", {
        category: 'categories'
    }
);

App.Store = DS.Store.extend({
    revision: 12,
    adapter: DS.RESTAdapter.create({
        url: 'app'
    })
});

App.Router.map(function(){
    this.resource('categories');
});

App.CategoriesRoute = Ember.Route.extend({
    model: function() {
        return App.Category.find();
    }
});

var attr = DS.attr;

App.Category = DS.Model.extend({
    name: attr('string')
});

现在这适用于测试服务器。 使用以下 JSON

{
    "categories":[
        {
            "name":"Beef",
            "id":1
        },
        {
            "name":"Pork",
            "id":2
        }
    ]
}

但在生产中,服务器提供以下 json:

{
    "success":true,
    "message":"Request successful",
    "total":2,
    "data":[
        {
            "name":"Beef",
            "id":1
        },
        {
            "name":"Pork",
            "id":2
        }
    ]
}

我这辈子都不知道如何使用序列化程序来使用实时 json。任何帮助,将不胜感激。提前致谢。

更新:

我已经尝试编写序列化程序,但它似乎没有工作......

见下文

App.Store = DS.Store.extend({
    revision: 12,
    adapter: DS.RESTAdapter.create({
        url: 'app',
        serializer: DS.RESTSerializer.extend({
            extract: function(loader, json, type, record) {
                var root = 'data';
                this.sideload(loader, type, json, root);
                this.extractMeta(loader, type, json);
                if (json[root]) {
                    if (record) { loader.updateId(record, json[root]); }
                    this.extractRecordRepresentation(loader, type, json[root]);
                }
            }
        })
    })
});

现在会产生此错误Uncaught Error: assertion failed: Your server returned a hash with the key data but you have no mapping for it

【问题讨论】:

    标签: javascript rest ember.js ember-data


    【解决方案1】:

    你有两个选择

    • 使您的服务器兼容,并让它按照 ember 数据的预期返回 json,
    • 编写您自己的适配器/序列化器来支持这种格式。

    更新:编写您自己的序列化程序 更新 2:摆脱未使用的功能

    https://github.com/emberjs/data/blob/master/packages/ember-data/lib/serializers/json_serializer.js#L196

    您可以从DS.RESTSerializer 继承并使用此代码更改extract

      extract: function(loader, json, type, record) {
        var root = 'data';
    
        if (json[root]) {
          if (record) { loader.updateId(record, json[root]); }
          this.extractRecordRepresentation(loader, type, json[root]);
        }
      }
    

    这假定请求的内容将始终在您的 json 的 data 键下。

    【讨论】:

    • 由于某种原因提取覆盖似乎没有触发:(
    • 您是否继承自DS.RESTSerializer 并在适配器上设置新的序列化程序?
    • 您好,我已经使用新的序列化程序代码编辑了问题,但它似乎没有按预期工作。
    • 问题是序列化器不知道接收到的数据类型是什么。我需要多想一点。
    • 由于序列化程序无法从 json 中推断出类型,因此适配器需要在发出 xhr 请求时捕获此信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-08
    • 1970-01-01
    • 1970-01-01
    • 2015-12-26
    相关资源
    最近更新 更多