我正在使用ember& ember-data尝试从服务器使用json feed。这是我的代码:
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
}
]
}
我不能为我的生活弄清楚如何使用序列化程序来使用live 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
答案 0 :(得分:3)
您有2个选项
更新:编写自己的序列化程序 更新2:摆脱未使用的功能
您可以继承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
密钥下。