RestApi的嵌入式数据 [英] Embedded data from RestApi
问题描述
我的数据来自REST API,如下所示:
My data comes from REST API like this:
customers:[
id:3,
name:"Joue",
currency:{
id:5
iso_code:"BDT"
}
]
我的模型:
App.Customer = DS.Model.extend({
name: DS.attr('string'),
currency: DS.attr('string')
});
我填充了一个可选择的货币的选择框,现在我想通过id选择5。
由于货币是嵌入的,它被解释为字符串我无法访问它。
据我所知,ember-data 1.0中不再支持嵌入式记录。
i populated a select box with the availabe currencies and now i want to select by "id" 5. Since currency is embedded and its interpreted as string i cant access it. As far as i know embedded records are no longer supported in ember-data 1.0.
我必须重写我的REST Api并摆脱关系或者有一个解决方法。
do i have to rewrite my REST Api and get rid of the relationships or there is a workaround .
推荐答案
您可以为数据创建自定义序列化程序。
You can just create a custom serializer for the data.
使用你的数据(稍微修改,因为json是无效的,我猜这只是因为它是手写的?)
Using your data (slightly modified, since the json isn't valid, and I'm guessing that's just cause it was hand written?)
{
customers:[
{
id:3,
name:"Joue",
currency:{
id:5,
iso_code:"BDT"
}
}
]
}
这是一个特定响应类型的序列化器(在这里阅读更多信息 https://github.com/emberjs/data/blob/master/TRANSITION.md )
Here's a serializer for that particular response type (read more about it here https://github.com/emberjs/data/blob/master/TRANSITION.md)
App.CustomerSerializer = DS.RESTSerializer.extend({
extractArray: function(store, type, payload, id, requestType) {
var customers = payload.customers,
currencies = [];
customers.forEach(function(cust) {
var currency = cust.currency;
delete cust.currency;
if(currency){
currencies.push(currency);
cust.currency = currency.id;
}
});
payload = { customers:customers, currencies: currencies };
return this._super(store, type, payload, id, requestType);
}
});
您使用关系定义的模型
App.Customer = DS.Model.extend({
name: DS.attr('string'),
currency: DS.belongsTo('currency')
});
App.Currency = DS.Model.extend({
iso_code: DS.attr('string')
});
示例:
http://emberjs.jsbin.com/OxIDiVU/535/edit
这篇关于RestApi的嵌入式数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!