/angular

Integrate Swagger UI inside Angular app

After spending alot of time on how to embed a swagger-ui inside an Angular application, I am documenting my findings here.

Package confusions

There are two packages that will be brought up when you lookup google swagger ui angular.

  • swagger-ui-dist
  • swagger-ui

I’ve read multiple blogs pointing to the swagger-ui-dist library and people who got it working. But I wasn’t able to get it working using this.

Then I used the swagger-ui package which has the similar code snippet. Something like below

 ngAfterViewInit() {
        const ui = SwaggerUI({
            url: 'https://petstore.swagger.io/v2/swagger.json',
            dom_id: '#swagger',
            presets: [
                SwaggerUI.presets.apis
            ]
        });
    }
<div #swagger></div>

And it still wasn’t working. I was not able to see anything on the UI. I thought I had missed to import the stylesheet but it was’nt the case. I already had imported it.

"styles": [ "./node_modules/swagger-ui/dist/swagger-ui.css"]

Here’s the working way. Notice the dom_id containing a viewchild reference ? There was another API in the swagger package which allows us to find the node instead of the id. So I tried it as it was being used on some threads on swagger-ui-repo

 ngAfterViewInit() {
        const ui = SwaggerUI({
            url: 'https://petstore.swagger.io/v2/swagger.json',
            domNode: document.getElementById('swagger'),
            presets: [
                SwaggerUI.presets.apis
            ]
        });
    }
<div id="swagger"></div>

Now it started to show up, but I was still getting console error that require is undefined withtin the swagger-ui.js

HariHaran

HariHaran

Full Stack Developer

Read More