Rob*_*bin 10 javascript ember.js ember-data
我有一个返回JSON的API,它没有为Ember的消费格式正确.而不是这(烬预期):
{ events: [
{ id: 1, title: "Event 1", description: "Learn Ember" },
{ id: 2, title: "Event 2", description: "Learn Ember 2" }
]}
Run Code Online (Sandbox Code Playgroud)
我明白了:
{ events: [
{ event: { id: 1, "Event 1", description: "Learn Ember" }},
{ event: { id: 2, "Event 2", description: "Learn Ember 2" }}
]}
Run Code Online (Sandbox Code Playgroud)
因此,如果我理解正确,我需要创建一个自定义Serializer来修改JSON.
var store = DS.Store.create({
adapter: DS.RESTAdapter.create({
serializer: DS.Serializer.create({
// which hook should I override??
})
})
});
Run Code Online (Sandbox Code Playgroud)
我已经阅读了与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);
}
Run Code Online (Sandbox Code Playgroud)
Yeh*_*atz 12
我假设响应仅包含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;
}
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8255 次 |
| 最近记录: |