我的 api api/customers
返回:
{
"value": [
{
"CustomerID": "ALFKI",
"CompanyName": "Alfreds Futterkiste",
"ContactName": "Maria Anders",
"ContactTitle": "Sales Representative",
"id": "b0d16ed0-c901-4ca3-ba41-7fc74c96909f"
},
{
"CustomerID": "ANATR",
"CompanyName": "Ana Trujillo Emparedados y helados",
"ContactName": "Ana Trujillo",
"ContactTitle": "Owner",
"id": "3f8ac226-9f78-42df-b337-0505f69792c3"
},
{
"CustomerID": "ANTON",
"CompanyName": "Antonio Moreno Taquería",
"ContactName": "Antonio Moreno",
"ContactTitle": "Owner",
"id": "09d31df6-69f4-43e4-9cc6-7faa5b8b5e3b"
}
]
}
但是 ember(/customers
) 应该期望:
{
"customers": [
{
"CustomerID": "ALFKI",
"CompanyName": "Alfreds Futterkiste",
"ContactName": "Maria Anders",
"ContactTitle": "Sales Representative",
"id": "b0d16ed0-c901-4ca3-ba41-7fc74c96909f"
},
{
"CustomerID": "ANATR",
"CompanyName": "Ana Trujillo Emparedados y helados",
"ContactName": "Ana Trujillo",
"ContactTitle": "Owner",
"id": "3f8ac226-9f78-42df-b337-0505f69792c3"
},
{
"CustomerID": "ANTON",
"CompanyName": "Antonio Moreno Taquería",
"ContactName": "Antonio Moreno",
"ContactTitle": "Owner",
"id": "09d31df6-69f4-43e4-9cc6-7faa5b8b5e3b"
}
]
}
我找到这个答案:GET unconventional JSON with Ember-data
所以我尝试(在我的 app/serializers/customers.js 中):
export default DS.RESTSerializer.extend({
extractArray: function(store, type, payload, id) {
var newpayload = { customers: payload.value };
return this._super(store, type, newpayload, id);
},
});
在 app/routes/customers.js 中
export default Ember.Route.extend({
model: function() {
return this.store.find('customer');
}
});
在 app/models/customer.js 中
export default DS.Model.extend({
CustomerID: DS.attr('string'),
CompanyName: DS.attr('string'),
ContactName: DS.attr('string'),
ContactTitle: DS.attr('string'),
});
在 app/templates/customers.hbs 中:
{{#each}}
{{CustomerID}}({{ContactName}}
{{/each}}
我打开浏览器,但它是空的,也没有错误信息,为什么它不起作用?
最佳答案
在序列化器中覆盖typeForRoot
:
typeForRoot: function(root) {
if (root === 'value') root = 'customers';
return this._super(root);
}
这里的问题是“根”键(JSON 中的顶级键,Ember Data 使用它来确定它应该是什么模型)是错误的,所以你需要 typeForRoot
来修补它。
(extractArray
做了一些不同的事情:它处理数组值属性。无论如何,修复 app/serializers/customers.js 是行不通的
(可能应该是 customer.js
)因为 Ember 在这个时间点甚至不知道涉及客户模型。)
关于javascript - 使用 Ember-data 序列化非常规 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30151665/