ember 数据序列化器数据映射 [英] ember data serializer data mapping
问题描述
我正在使用 ember &ember-data 尝试使用来自服务器的 json 提要.这是我的代码:
I'm using ember & ember-data to try and consume a json feed from the server. Here is my code:
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
Now this works fine with a testing server. Using the following JSON
{
"categories":[
{
"name":"Beef",
"id":1
},
{
"name":"Pork",
"id":2
}
]
}
但是在生产中,服务器提供以下 json:
However in production the server provide the following json:
{
"success":true,
"message":"Request successful",
"total":2,
"data":[
{
"name":"Beef",
"id":1
},
{
"name":"Pork",
"id":2
}
]
}
我一生都无法弄清楚如何使用序列化程序来使用实时 json.任何帮助,将不胜感激.提前致谢.
I can't for the life of me work out how to use the serializer to consume the live json. Any help would be appreciated. Thanks in advance.
更新:
此后我尝试编写序列化程序,但它似乎不起作用...
I've since tried to write the serializer but it doesn't appear to be working...
见下文
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: 你的服务器返回了一个带有关键数据的哈希值,但你没有映射它
推荐答案
您有 2 个选择
- 使您的服务器兼容,并让它按照 ember 数据的预期返回 json,
- 编写您自己的适配器/串行器来支持这种格式.
更新:编写自己的序列化程序更新 2:删除未使用的函数
UPDATE: write your own serializer UPDATE 2: get rid of unused functions
您可以从 DS.RESTSerializer
继承并使用此代码更改 extract
You can inherit from the DS.RESTSerializer
and change extract
with this code
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
键下.
This assumes that the content of request will always be under the data
key of your json.
这篇关于ember 数据序列化器数据映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!