Angular 6+页面中重复显示Swagger Editor的问题求助
解决Angular 6+中双Swagger Editor实例渲染问题
你遇到的核心问题其实很明确:重复的DOM ID和选择器拼写不匹配,这两个问题导致只有第一个Swagger Editor实例能正常渲染。下面一步步帮你修复:
1. 修复重复的DOM ID
HTML里两个容器的id都是swagger-editorInbox,但DOM中id必须是唯一的——Swagger Editor初始化时只会绑定第一个匹配到的id,第二个容器自然就无法被识别。我们需要给两个容器分配不同的唯一id:
- 把模态框内的容器id改为
swagger-editor-modal - 保留下方容器的id为
swagger-editor-inbox(或者换成你喜欢的其他唯一名称)
2. 修正TS中的选择器拼写错误
你在代码里写的dom_id: "#swagger_editorInbox"用了下划线,但HTML里的id是横杠连接的swagger-editorInbox,拼写不匹配直接导致Swagger Editor找不到目标容器。同时,我们需要初始化两个独立的Editor实例,分别对应两个容器。
修改后的完整代码
app.component.html
<div class="form-group"> <i class="fa fa-expand" data-toggle="modal" data-target="#exampleModalCenter"></i> <!-- Modal --> <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">Swagger of </h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> <div class="col-12"> <div id="swagger-editor-modal" style="height:500px"></div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> <div class="row" style="border:solid 1px gray"> <div id="swagger-editor-inbox" style="height:500px"></div> </div> </div>
app.component.ts
declare const SwaggerEditorBundle: any; // 注意:Angular类名建议用大驼峰命名,比如SwaggerComponent,遵循框架规范 export class SwaggerComponent implements OnInit { editorModal: any; editorInbox: any; // 你的Swagger定义 mySwagger = '....//my swagger// ...'; ngOnInit() { // 初始化模态框内的Editor实例 this.editorModal = SwaggerEditorBundle({ dom_id: "#swagger-editor-modal" }); this.editorModal.specActions.updateSpec(this.mySwagger); // 初始化下方的Editor实例 this.editorInbox = SwaggerEditorBundle({ dom_id: "#swagger-editor-inbox" }); this.editorInbox.specActions.updateSpec(this.mySwagger); } }
额外优化提示
- 如果需要两个编辑器保持内容同步(比如修改一个另一个自动更新),可以监听其中一个的spec变化事件,同步更新另一个的内容:
// 监听模态框编辑器的内容变化,同步到下方编辑器 this.editorModal.specActions.subscribe((spec: any) => { this.editorInbox.specActions.updateSpec(spec); });
内容的提问来源于stack exchange,提问作者Techdive
相关产品推荐
相关产品推荐

