将Swagger UI添加到Angular应用程序

10

有没有一个好方法可以将Swagger UI添加到Angular应用程序中,而不会太深入细节?

我想要添加对托管在不同站点上的API的引用,所以我只需要UI元素来引用文档。

我发现了一个名为Swangular-Components的包,但它似乎会破坏我的index.d.ts文件。像那样的解决方案对于我的情况来说是最简单的,我想。


这个仓库展示了如何在 Angular 应用中使用 Swagger UI Node 模块 https://github.com/agoncal/swagger-ui-angular6 - Chris
我通过将其添加到 Express 服务器中找到了一个好方法。 - Christian Matthew
2个回答

10

我曾经多次遇到这个问题,但最终找到了一种解决方法,主要是因为我偶然发现了将Swagger编辑器添加到Angular项目中的问题(https://dev59.com/u7Xna4cB1Zd3GeqPNJFi#57431950)。需要对Swagger UI进行微调,但最终使其正常工作。

安装swagger-ui-dist

npm install swagger-ui-dist --save

配置angular.json文件和所需的Swagger-UI组件。

// angular.json

"styles": [
    "node_modules/swagger-ui-dist/swagger-ui.css",
    "src/styles.css"
],
"scripts": [
    "node_modules/swagger-ui-dist/swagger-ui-bundle.js",
    "node_modules/swagger-ui-dist/swagger-ui-standalone-preset.js"
]
// component.ts

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

declare const SwaggerUIBundle: any;

@Component({
  selector: 'app-swagger-ui',
  templateUrl: './swagger-ui.component.html',
  styleUrls: ['./swagger-ui.component.css']
})
export class SwaggerUiComponent implements OnInit {

  ngOnInit(): void {
    const ui = SwaggerUIBundle({
      dom_id: '#swagger-ui',
      layout: 'BaseLayout',
      presets: [
        SwaggerUIBundle.presets.apis,
        SwaggerUIBundle.SwaggerUIStandalonePreset
      ],
      url: 'https://petstore.swagger.io/v2/swagger.json',
      docExpansion: 'none',
      operationsSorter: 'alpha'
    });
  }
}
// component.html

<div id="swagger-ui"></div>

示例应用的Github仓库: https://github.com/ostranme/angular-swagger-ui-example


1
我也做了同样的事情,但出现了“SwaggerUIBundle未定义”的错误。你能帮我吗? - Ilya Berdzenishvili
1
我和@IlyaBerdzenishvili遇到了相同的错误。你们解决了吗? - Lee Merlas
它对我有效,但别忘了在编辑“angular.json”后重新启动你的“ng serve”。 - Laurent Trillaud

2

这篇文章已经发布8个月了,所以我假设您已经解决了问题或者转而寻找其他解决方案。但是,您可以使用Renderer2基本地实现这一点,即使不太理想。您只需要创建一个包含Swagger-ui配置和外部文档链接的脚本元素,然后使用Renderer2将标签添加到组件中。我正在使用这种方法将Swagger-ui嵌入到Angular应用程序中,以允许用户在不同的API文档之间进行选择。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接