gpt4 book ai didi

javascript - 使用 RestSerializer 返回多态负载

转载 作者:行者123 更新时间:2023-11-30 17:04:29 26 4
gpt4 key购买 nike

假设我有以下多态关系:

//animal.js
export default DS.Model.extend({});

//dog.js
import Animal from './animal';
export default Animal.extend({});

//cat.js
import Animal from './animal';
export default Animal.extend({});

//bird.js
import Animal from './animal';
export default Animal.extend({});

现在我要获取所有的动物。

this.store.find('animal');

假设我希望每个多态记录都转换到其各自的类中,默认 RestSerializer 的 JSON 响应应该是什么?目前,我所有的记录都被转换为动物实例,而不是它们的正确类型。

最佳答案

当一个关系是多态的时,服务器响应应该指出返回对象的 ID 和类型(RESTSerializer 默认这样做);例如:

{
"animals": [
{
// ... other attributes
"type": "dog" // attribute that tells ember data what kind of Animal to instantiate
},
{
// ... other attributes
"type": "cat" // attribute that tells ember data what kind of Animal to instantiate
},
{
// ... other attributes
"type": "bird" // attribute that tells ember data what kind of Animal to instantiate
},
]
}

这意味着当加载数据时,ember-data 应该根据数据中包含的“类型”实例化正确的 Animal 对象。 (假设 Animal 模型声明了属性 polymorphic: true)

这里有一些有用的例子:


编辑

您需要配置您的模型,使它们具有多态性。在您的情况下,您可以只添加一个父对象,例如 Zoo ,其中包含许多 Animal 对象:

//zoo.js
export default DS.Model.extend({
animals: DS.hasMany('animal', { polymorphic: true });
});

//animal.js
export default DS.Model.extend({
zoo: DS.belongsTo('zoo');
});

//dog.js
import Animal from './animal';
export default Animal.extend({
// attributes ...
});

//cat.js
import Animal from './animal';
export default Animal.extend({
// attributes ...
});

//bird.js
import Animal from './animal';
export default Animal.extend({
// attributes ...
});

现在您可以将 Zoo 模型添加到您的 JSON 中,其中包含 Animal 对象的多态数组的 ID:

"zoos": [{
"id": 1,
"animals": [123, 456, 789], // animal ids
}],
"animals": [{
"id": 123,
"type": "dog" // attribute that tells ember data what kind of Animal to instantiate
// ... other attributes
},{
"id": 456,
"type": "cat" // attribute that tells ember data what kind of Animal to instantiate
// ... other attributes
},{
"id": 789,
"type": "bird" // attribute that tells ember data what kind of Animal to instantiate
// ... other attributes
}]

您会像 store.find('zoo', 1) 那样请求此 JSON。

这是一个有用的应用程序,可帮助您了解如何根据您的模型构建 JSON 响应。 ---> LINK

Another useful example for ember-data polymorphism

关于javascript - 使用 RestSerializer 返回多态负载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28270937/

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