【发布时间】:2019-10-17 07:55:56
【问题描述】:
前言:这个项目有很多第一次,比如构建我的第一个API,第一次使用JSON API,第一次使用Ember,第一次在SO上发帖等等。
我正在尝试访问包含最新更新的模板中的“作者”hasMany 属性。我在模板中访问它,但是,没有返回任何内容。模型已正确保存,但似乎未设置关系,因为 latest.contentAuthors 上的 DS.PromiseManyArray 的长度为 0,而承诺已履行 ({ _length: 0, isFulfilled: true, isRejected: false })。
我使用的是 Ember 3.10(带有 CLI)。我可以完全控制我的后端(运行 ExpressionEngine 5 的 LAMP),并通过自定义构建的插件提供 API 请求,但我不确定这是否重要,因为这在很大程度上是我能辨别的前端问题。
路线
import Route from '@ember/routing/route';
export default Route.extend({
model(){
let latest = this.store.peekAll('latest');
if (latest.length < 2){
latest = this.store.query('latest', { limit: 2, include: "people" });
}
return latest;
}
});
基础模型
import DS from 'ember-data';
const { Model } = DS;
export default Model.extend({
title: DS.attr()
});
最新模型
编辑:删除了不在原始代码中的冗余属性
import DS from 'ember-data';
import ExpressionEngineBase from './expression-engine-base';
export default ExpressionEngineBase.extend({
blurb: DS.attr(),
contentAuthors: DS.hasMany('person')
});
人物模型
编辑:删除了不在原始代码中的冗余属性
import DS from 'ember-data';
import ExpressionEngineBase from './expression-engine-base';
export default ExpressionEngineBase.extend({
latest: DS.hasMany('latest')
});
模板
{{#each this.model as |latest|}}
<h2>{{latest.title}}</h2>
{{#each latest.contentAuthors as |author|}}
<div>{{author.title}}</div>
{{else}}
<div>Can't find author(s)</div>
{{/each}}
<p>{{latest.blurb}}</p>
{{/each}}
从服务器发送的数据
编辑: 对照JSON API validator 进行检查,发现原始数据不符合要求。我已经更新了我的后端,但这并没有解决问题。这现在符合该验证器。
{
"data": [{
"id": "3161",
"type": "latest",
"attributes": {
"title": "Amazing Video 1"
},
"links": {
"self": "https:\/\/cms.example.com\/api\/v1\/video\/3161"
},
"relationships": {
"people": {
"data": [{
"id": "1",
"type": "people"
}]
}
}
}, {
"id": "2573",
"type": "latest",
"attributes": {
"title": "Amazing Article 1"
},
"links": {
"self": "https:\/\/cms.example.com\/api\/v1\/white_papers_insights\/2573"
},
"relationships": {
"people": {
"data": [{
"id": "1",
"type": "people"
}, {
"id": "52",
"type": "people"
}]
}
}
}],
"links": {
"self": "https:\/\/cms.example.com\/api\/v1\/latest?include=people&limit=2"
},
"included": [{
"id": "1",
"type": "people",
"links": {
"self": "https:\/\/cms.example.com\/api\/v1\/people\/1",
"channel": "https:\/\/cms.example.com\/api\/v1\/people"
},
"attributes": {
"title": "Great Author"
}
}, {
"id": "52",
"type": "people",
"links": {
"self": "https:\/\/cms.example.com\/api\/v1\/people\/52",
"channel": "https:\/\/cms.example.com\/api\/v1\/people"
},
"attributes": {
"title": "Great Co-Author"
}
}]
}
重申一下,关系模型正在保存并且可以在 Ember Inspector 中查看,但没有设置实际的链接/关系。
更新:我尝试重命名类型和查询参数无济于事,检查屈折变化是否与丢弃的关系有关。
【问题讨论】:
标签: ember.js ember-data