当我通过const myRecord = this.store.createRecord('myType', myObject)
和myRecord.save()
创建记录时,请求会通过适配器发送到服务器。数据已成功保存,服务器将所有数据返回给客户端。它通过normalize()
钩子返回到串行器。
问题是Ember没有用服务器返回的属性更新myRecord
对象,例如id
或version
。。。
当我刷新页面时,所有属性都在那里(当然)。
我在更新记录方面也有类似的问题。我的应用程序中的每个记录都有一个由服务器检查的版本属性。每次保存时版本都会递增。这是为了数据安全。问题是,当我尝试多次更新记录时,只有第一次尝试成功。原因是请求从服务器返回后version
没有更新。(是的,服务器返回更新版本)
这对我来说是一个令人惊讶的行为,在我看来,这就像是这里建议的一个预期功能——https://github.com/ebryn/ember-model/issues/265.(但那个帖子是2013年的,建议的解决方案对我不起作用)。
有什么想法吗?
对于completenes,以下是相关代码(简化并重命名)
myModel
export default Ember.Model.extend({
typedId: attr('string') // this serves as an ID
version: attr('string'),
name: attr('string'),
markup: attr('number'),
});
myAdapter
RESTAdapter.extend({
createRecord(store, type, snapshot) {
// call to serializer
const serializedData = this.serialize(snapshot, options);
const url = 'http://some_internal_api_url';
// this returns a promise
const result = this.ajax(url, 'POST', serializedData);
return result;
},
});
mySerializer
JSONSerializer.extend({
idAttribute: 'typedId',
serialize(snapshot, options) {
var json = this._super(...arguments);
// perform some custom operations
// on the json
return json;
},
normalize(typeClass, hash) {
hash.data.id = hash.data.typedId;
hash.data.markup = hash.data.attribute1;
hash.data.version = parseInt(hash.data.version, 10);
return hash;
}
});
根本原因在于序列化程序的normalize()
方法。应该调用this._super.apply(this, arguments);
,然后将更改写入数据存储。否则,它们不会反映在那里。请参阅文档http://emberjs.com/api/data/classes/DS.JSONSerializer.html#method_normalize
所以工作代码看起来像这个
normalize(typeClass, hash) {
hash.data.id = hash.data.typedId;
hash.data.markup = hash.data.attribute1;
hash.data.version = parseInt(hash.data.version, 10);
return this._super.apply(this, [typeClass, hash.data]);
}
很可能您将此版本称为
return this._super.apply(this, arguments);