(免责声明,我不是JS专家。目前正在学习和实践。如果我犯了任何错误,请原谅。但请帮助我)
我一直在尝试为现有的 Autodesk Forge Hubs 代码实现新功能。我想从响应正文的
derivatives.data.id
对象中检索 relationships
。响应正文来自 API
`GET /api/hubs/${hubId}/projects/${projectId}/contents/${itemId}/versions`
为了解释我的问题,我将把代码片段设置为
before
和 after
之前:
function createTreeNode(id, text, icon, children = false) {
return { id, text, children, itree: { icon } };
}
async function getVersions(hubId, projectId, itemId) {
const versions = await getJSON(`/api/hubs/${hubId}/projects/${projectId}/contents/${itemId}/versions`);
return versions.map(version => createTreeNode(`version|${version.id}`, version.attributes.createTime, 'icon-version'));
}
之后(修改代码):
function createTreeNode(id, text, icon, children = false, derivativesId = null) {
return { id, text, children, itree: { icon, derivativesId } };
}
async function getVersions(hubId, projectId, itemId) {
const versions = await getJSON(`/api/hubs/${hubId}/projects/${projectId}/contents/${itemId}/versions`);
versions.forEach(version => {
const { id, attributes,relationships } = version;
const derivativesId = relationships?.derivatives?.data?.id || null;
console.log(`Version ID: ${id}`, `Derivatives ID: ${derivativesId}`);
});
return versions.map(version => {
const { id, attributes,relationships} = version;
const derivativesId = relationships?.derivatives?.data?.id || null; // Extract 'id' from 'derivatives' object
return createTreeNode(`version|${id}`, attributes.createTime, 'icon-version', derivativesId);
});
}
这是autodesk的原始代码:https://raw.githubusercontent.com/autodesk-platform-services/aps-hubs-browser-nodejs/develop/wwwroot/sidebar.js
我犯了什么错误,为什么它没有加载树?
我知道有两个版本(响应主体)在
derivatives
内没有 relationships
。这是否导致树继续循环或者错误是什么?遇到这种情况该如何处理?
预先感谢您的帮助!
您是否可以分享运行第二个场景时得到的调试结果。 发生该错误的原因可能是您期望的derivativeId 不存在于响应中。 您还可以在获取derivativeId时尝试使用nullish合并运算符
我找出了问题的原因。当存在空值时,将
derivativesId
放置在 createTreeNode
中会停止树负载。
function createTreeNode(id, text, icon, children = false, derivativesId = null) {
return { id, text, children, itree: { icon, derivativesId } };
}
答案:
function createTreeNode(id, text, icon, children = false, derivativesId = null) {
return { id, text, children, itree: { icon}, derivativesId } };
}