我知道如果我想序列化名为post的模型的嵌套注释,我需要在app / serializer / post.js中创建一个序列化器 类似的东西:
import RESTSerializer from 'ember-data/serializers/rest';
import DS from 'ember-data';
export default RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
comments: {embedded: 'always'}
}
});
但如果我想在app / serlizer / application.js中序列化该怎么办? 我不想为每个模型定义一个序列化器。相反,我希望能够解析normalizeQueryResponse中的所有或多次关系。
normalizeQueryResponse(store, primaryModelClass, payload, id, requestType) {
console.log(payload);
return this._normalizeResponse(store, primaryModelClass, payload, id, requestType, true);
},
我希望能够彻底完成有效载荷,如果有效载荷中的属性被证明是对象,那么解决它。
有人知道这是否可能?
答案 0 :(得分:0)
当然这是可能的,它的序列化器和模型是如何工作的。但我建议依靠一个模型,而不是在你的情况下指定类型。让我们举个例子。
你的模型post.js
export default DS.Model.extend((
valueA: DS.attr('string'), // converted to string
valueB: DS.attr('boolean'), // converted to boolean
comments: DS.attr() // not converted and set as it came in the payload
));
你的序列化器post.js
export default RESTSerializer.extend({
// assuming your payload comes in the format of
// { data: [ {id: 0, valueA: '', valueB: true, comments: [...]}, {id:1 ...} ]
normalizeQueryResponse(store, primaryModelClass, payload, id, requestType) {
payload.data = payload.data.map((item, index) => ({ // item = {event_type: '', values: ['','']}
id: index, // ONLY if your payload doesnt already have an id
type: 'post', // set the model type
attributes: { // attributes are the values declared in the model
valyeA: item.valueA,
valueB: item.valueB,
comments: item.comments.map( item => {
// remap your comments to whatever format you need
})
}
}));
return payload;
});
在您的应用中使用
this.get('store').query('post', {...query object...} ).then(
response => {
let firstItemLoadedComments = response.get('firstObject.values');
// blast comments!
},
error => {
Ember.Logger.error(`cannot load model: ${error}`);
})
.finally(() => {
// set loading to false or something else
});