有没有一个好方法可以将Swagger UI添加到Angular应用程序中,而不会太深入细节?
我想要添加对托管在不同站点上的API的引用,所以我只需要UI元素来引用文档。
我发现了一个名为Swangular-Components的包,但它似乎会破坏我的index.d.ts文件。像那样的解决方案对于我的情况来说是最简单的,我想。
有没有一个好方法可以将Swagger UI添加到Angular应用程序中,而不会太深入细节?
我想要添加对托管在不同站点上的API的引用,所以我只需要UI元素来引用文档。
我发现了一个名为Swangular-Components的包,但它似乎会破坏我的index.d.ts文件。像那样的解决方案对于我的情况来说是最简单的,我想。
我曾经多次遇到这个问题,但最终找到了一种解决方法,主要是因为我偶然发现了将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
这篇文章已经发布8个月了,所以我假设您已经解决了问题或者转而寻找其他解决方案。但是,您可以使用Renderer2基本地实现这一点,即使不太理想。您只需要创建一个包含Swagger-ui配置和外部文档链接的脚本元素,然后使用Renderer2将标签添加到组件中。我正在使用这种方法将Swagger-ui嵌入到Angular应用程序中,以允许用户在不同的API文档之间进行选择。