我正在使用emberJS来显示从REST API获取的数据。我的ember应用程序连接到REST服务器并且服务器返回JSON数据,但是当我尝试在模板中显示我的餐馆的id时,我得到了这个输出:
Restaurant id is:
以下是我的模特:
import DS from 'ember-data';
//restaurant.js model
export default DS.Model.extend({
restaurantId: DS.attr('int'),
name: DS.attr('string'),
rating: DS.attr('double'),
phone: DS.attr('double'),
reservationPrice: DS.attr('double'),
workingHours: DS.attr('string'),
deals: DS.attr('string'),
image: DS.attr('string'),
//Relations
coordinates: DS.belongsTo('coordinates'),
address: DS.belongsTo('address')
});
//coordinates.js model
import DS from 'ember-data';
export default DS.Model.extend({
latitude: DS.attr("double"),
longitude: DS.attr("double"),
//Relations
restaurant: DS.belongsTo('restaurant')
});
//address.js model
import DS from 'ember-data';
export default DS.Model.extend({
streetName: DS.attr("string"),
city: DS.attr("string"),
country: DS.attr("string"),
//Relations
restaurant: DS.belongsTo('restaurant')
});
我的模板:
Restaurant id is: <br>
{{restaurant.restaurantId}}
<br>
{{model.restaurantId}}
{{#each model as |restaurant|}}
<h2>{{restaurant.image}}</h2>
{{/each}}
和我的路线:
//restaurant.js route
import Ember from 'ember';
export default Ember.Route.extend({
model() {
return this.store.findAll('restaurant');
}
});
当然还有我的序列化器:
import DS from 'ember-data';
export default DS.RESTSerializer.extend({
normalizeFindAllResponse(store, type, payload){
return {
id: "restaurantId",
data: {
type: type.modelName,
id: "restaurantId",
attributes: {
id: "restaurantId",
restaurantId: payload.restaurantId,
name: payload.name,
address: payload.address,
phone: payload.phone,
workingHours: payload.workingHours,
rating: payload.rating,
image: payload.image
}
}
};
}
});
这是我从服务器获得的JSON:
[ {
"restaurantId" : 1,
"name" : "Some name",
"address" : {
"streetName" : "some street",
"city" : "some town",
"country" : "some country"
},
"phone" : 984894,
"workingHours" : "08:00 - 23:00",
"rating" : 3.0,
"image" : "www.somelink.com"
},
...
]
我可以在Chrome检查器中看到我的ember App向服务器发出请求,服务器使用JSON进行响应。并且没有错误或警告,但我的模型数据不会显示。任何帮助表示赞赏。
修改
我在我的序列化程序中写了这个normalizeFindRecord,现在它看起来像这样:
normalizeFindRecordResponse(store, type, payload){
return {
data: {
type: type.modelName,
id: "restaurantId",
address: DS.belongsTo('restaurant', {embedded: true} ),
attributes: {
restaurantId: payload.restaurantId,
name: payload.name,
address: payload.address,
phone: payload.phone,
workingHours: payload.workingHours,
rating: payload.rating,
image: payload.image,
coordinates: payload.coordinates
}
}
};
}
现在当我尝试路线this.store.findRecord('restaurant', 1);
时,我得到了
Restaurant id is:
1
但是findAllRoute仍无效。