Dav*_*bec 1 ember.js ember-data
当我创建一个记录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'),
});
Run Code Online (Sandbox Code Playgroud)
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;
},
});
Run Code Online (Sandbox Code Playgroud)
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;
}
});
Run Code Online (Sandbox Code Playgroud)
根本原因在于序列化程序的normalize()方法.应该调用this._super.apply(this, arguments);然后写入Data Store中的更改.否则他们不会反映在那里.请参阅文档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]);
}
Run Code Online (Sandbox Code Playgroud)
你最有可能称之为这个版本
return this._super.apply(this, arguments);
Run Code Online (Sandbox Code Playgroud)