gpt4 book ai didi

javascript - 使用嵌入式记录和 Ember 数据

转载 作者:行者123 更新时间:2023-11-28 07:18:03 25 4
gpt4 key购买 nike

我正在使用 Ember 和 Ember Data,我从服务器返回的 JSON 包含一个嵌入的对象数组。我需要知道我做错了什么。我有一个 JSBin,代码如下:

http://emberjs.jsbin.com/faledu/6/edit?html,js,output

目前,我收到以下错误:

Error while processing route: index Assertion Failed: Ember Data expected a number or string to represent the record(s) in the objects relationship instead it found an object. If this is a polymorphic relationship please specify a type key. If this is an embedded relationship please include the DS.EmbeddedRecordsMixin and specify the objects property in your serializer's attrs object. Error: Assertion Failed: Ember Data expected a number or string to represent the record(s) in the objects relationship instead it found an object. If this is a polymorphic relationship please specify a type key. If this is an embedded relationship please include the DS.EmbeddedRecordsMixin and specify the objects property in your serializer's attrs object.

我在序列化器中使用 DS.EmbeddedRecordsMixin,但它似乎不起作用。如何将该 JSON 与 Ember 数据一起使用?

最佳答案

您可以添加自定义array转换供ember-data使用,并通过消除对EmbeddedRecordsMixin等的需求来极大地简化您的代码。

http://emberjs.jsbin.com/warebi/1/edit

这是我过去经常使用的数组转换:

App.ArrayTransform = DS.Transform.extend({
deserialize: function(serialized) {
return (Ember.typeOf(serialized) === 'array') ? serialized : [];
},

serialize: function(deserialized) {
var type = Ember.typeOf(deserialized);
if (type === 'array') {
return deserialized;
} else if (type === 'string') {
return deserialized.split(',').map(function(item) {
return item.trim();
});
} else {
return [];
}
}
});

但是,我要说的是,在结构方面,您确实应该避免与 ember-data 发生冲突。我尝试过强制执行边缘情况,但最终做了比需要的更多的工作。如果您无法修改 API 以使其更加“JSON API”友好,我会考虑寻找 ember-data 的其他替代方案,或者考虑仅使用纯 AJAX 来处理类似于 Discourse 方法的事情。归根结底,我只是尝试确保您的 API 以侧面加载方式工作,或者使用 async 方法在两个单独的请求中工作。您的生活将会更加轻松。

"design": {
"id": "1",
"name": "test1",
"description": "testing",
"objects": [1, 2]
},
"objects": [
{
"id": 1,
"name": "foo"
},
{
"id": 2,
"name": "bar"
}
]

这是一篇旧博客文章,但如果您的用例需要在 ember-data 快乐路径之外运行,则主要概念仍然适用 - http://eviltrout.com/2013/03/23/ember-without-data.html

关于javascript - 使用嵌入式记录和 Ember 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30622363/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com