javascript - 操作未渲染的 DOM 元素以在 Angular 中导出
问题描述
我创建了一个 Angular 服务来为用户导出一个 SVGElement。简而言之,它构建了一个 SVG 并将符号附加到<defs>
. 然后,服务使用 Promise 将此 SVG 返回给组件,组件将其复制到剪贴板或将其导出为文件。
我的问题是导出的 SVG 元素在组件尝试导出它时为空。setTimeout()
如果我在服务中插入 a resolve(svgElement)
,它就可以工作。
如何以更同步的方式操作这些动态生成的 DOM 元素?SVG 永远不会为用户呈现。
这是一些简化的代码来尝试说明功能。
\\ service.ts
public exportToSVG(ids: string[]): Promise<SVGElement> {
return new Promise((resolve, reject) => {
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
const defs = document.createElement('defs');
ids.forEach(async id => {
// use another method to get the symbol associated with the id
const symbol = await this._getSymbolByString(id);
defs.appendChild(symbol);
});
svg.appendChild(defs);
resolve(svg);
});
}
\\ component.ts
public copyToClipboard(ids: string[]) {
this.myService.exportToSVG(ids).then(svg => {
// this only copies `<svg><defs></defs></svg>`, unless a setTimeout is used
this.clipboardService.copyFromContent(svg.outerHTML);
});
}
解决方案
我通过链接 Promises 解决了这个问题,而不是使用异步...等待。
推荐阅读
- c# - 在 phpmyadmin 中重新创建用户后:来自 c# 应用程序的“用户 'root'@'name_of_computer' 的访问被拒绝”
- c# - 将类序列化为单个字符串
- sql - 谷歌查询 - “不喜欢”声明不起作用
- visual-studio-code - 将光标(插入符号)移动到当前视图
- r - 循环遍历变量并进行置换意味着每个变量的差异测试
- reactjs - 我们如何配置 dotnet core react 应用程序以使用多条目?
- c# - 在编写 DefaultTrackableEventHandler.cs 脚本时,如何修复“成员修饰符“受保护”必须位于成员类型和名称之前
- c - C列表多线程同步
- java - java.lang.NoClassDefFoundError: org/eclipse/jetty/server/Handler
- python - 如何使用for循环使用python脚本将值1-100插入redis?