Adding Swagger UI to Angular App

后端 未结 2 884
小蘑菇
小蘑菇 2021-01-12 05:50

Is there a good way to add the Swagger UI to an Angular app without getting too much in the weeds?

I\'d like to add a reference to an API which is hosted on a differ

相关标签:
2条回答
  • 2021-01-12 06:27

    I've struggled with this numerous times but finally figured out somewhat of a solution mainly because I stumbled across this issue of adding swagger-editor to an angular project (https://stackoverflow.com/a/57431950/5641007). Had to tweak it a bit for swagger ui but ultimately got it working.

    Install swagger-ui-dist

    npm install swagger-ui-dist --save

    Configure the angular.json file and desired component for 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 repo for example app: https://github.com/ostranme/angular-swagger-ui-example

    0 讨论(0)
  • 2021-01-12 06:48

    This is 8 months old now so I'm assuming you figured it out or moved on, but it's possible to do this in a basic, if not ideal, way using Renderer2. You'd basically create a script element containing the config for swagger-ui and a link to the external doc, then use Renderer2 to append the tag to your component. I'm using this now as a way to embed the swagger-ui in an angular app that allows the user to choose between different api docs.

    0 讨论(0)
提交回复
热议问题