You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular项目中Redoc内容无法渲染的问题求助

Angular项目集成Redoc无法渲染问题

我正尝试在Angular项目中集成Redoc,但Redoc内容始终无法渲染。以下是我已经执行的操作:

1. angular.json配置

在scripts数组中引入Redoc独立脚本:

"scripts": [
  "src/assets/js/redoc.standalone.js"
]

2. 测试组件代码

dashboard.component.ts

import { Component, OnInit } from '@angular/core';

declare var Redoc: any;

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.scss']
})
export class DashboardComponent implements OnInit {

  constructor() { }

  ngOnInit() {
    this.initDocs();
  }

  initDocs(){
    Redoc.init('http://petstore.swagger.io/v2/swagger.json', {
      scrollYOffset: 60,
      hideDownloadButton: true
    }, document.getElementById('redoc'))
  }

}

dashboard.component.html

<mat-toolbar color="primary">
  <span>Dashboard</span>
</mat-toolbar>

<p>
  dashboard works!
</p>

3. 相关截图与日志

仪表盘页面显示

仪表盘页面截图

控制台日志

控制台日志截图

控制台渲染的HTML结构

渲染后的HTML结构截图


问题分析与解决办法

核心问题

你的initDocs方法里尝试获取id="redoc"的DOM元素,但dashboard.component.html中完全没有这个挂载容器,Redoc没有渲染目标,自然无法显示内容。

具体修复步骤

  1. 在HTML中添加Redoc挂载容器:
<mat-toolbar color="primary">
  <span>Dashboard</span>
</mat-toolbar>

<p>
  dashboard works!
</p>
<!-- 新增Redoc挂载容器 -->
<div id="redoc"></div>
  1. 确保DOM完全就绪后再初始化Redoc
    将初始化逻辑移到ngAfterViewInit钩子(比ngOnInit更晚执行,确保DOM已完全渲染):
import { Component, OnInit, AfterViewInit } from '@angular/core';

declare var Redoc: any;

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.scss']
})
export class DashboardComponent implements OnInit, AfterViewInit {

  constructor() { }

  ngOnInit() { }

  ngAfterViewInit() {
    this.initDocs();
  }

  initDocs(){
    Redoc.init('http://petstore.swagger.io/v2/swagger.json', {
      scrollYOffset: 60,
      hideDownloadButton: true
    }, document.getElementById('redoc'))
  }

}
  1. 跨域问题排查(可选)
    如果后续仍无法加载Swagger JSON,需检查目标API是否允许跨域请求,可通过Angular代理配置解决跨域限制。

内容的提问来源于stack exchange,提问作者Philip Mutua

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 10:56:22