添加角度为 10 的 swagger-UI

Ank*_*wat 7 swagger single-page-application reactjs swagger-ui angular

如何在 Angular 应用程序中添加Swagger UI ?

我已经多次搜索这个问题,发现只有一个解决方案,并且它是使用swagger-ui-dist包完成的,但在最新版本中https://www.npmjs.com/package/swagger-ui告诉我们使用swagger-ui而不是swagger-ui-dist单页应用程序。

有一个解决方案是添加这个包来进行反应,并且解释得很好。

Swagger-UI 与 React - https://swagger.io/blog/api-documentation/building-documentation-portal-swagger-tutorial/

Ank*_*wat 11

我在我的角度应用程序中实现了此功能,并认为它对其他开发人员也有帮助。我在多个地方进行了搜索并阅读了多个博客。

脚步 -

  1. 安装 swagger-ui

    npm i swagger-ui

  2. 配置 angular.json 文件和 swagger-ui CSS 模块。

  "styles": [ "./node_modules/swagger-ui/dist/swagger-ui.css"]
Run Code Online (Sandbox Code Playgroud)
  1. 将 swagger-UI 的 import 语句添加到您的 component.ts 文件中。

    import SwaggerUI from 'swagger-ui';

  2. 将以下代码添加到组件的 ngOnInit 中。

// example-swagger-exp.component.ts
ngOnInit() {
     SwaggerUI({
         domNode: document.getElementById('swagger-ui-item'),
         url: 'https://petstore.swagger.io/v2/swagger.json'
       });
 }
Run Code Online (Sandbox Code Playgroud)
  1. 此功能的最后一部分,将以下代码添加到组件的 HTML 文件中

    // swagger-exp.component.html

    <div id="swagger-ui-item"></div>
    
    Run Code Online (Sandbox Code Playgroud)

注意- 最后一件重要的事情,

如何在步骤 4 中添加 swagger.json/swagger.yaml 对象?

只需将“url”参数替换为“spec”并添加 JSON 对象即可。

      SwaggerUI({
          domNode: document.getElementById('api-data'),
          spec : your json object
        });
Run Code Online (Sandbox Code Playgroud)