swagger-ui icon indicating copy to clipboard operation
swagger-ui copied to clipboard

Unable to initialize SwaggerUIBundle in Angular 4 project

Open asakalou opened this issue 9 years ago • 17 comments

Trying to use swagger-ui-dist inside angular4 application. Initialization of SwaggerUIBundle produces an error (promise is overwritten error is thrown from zone.js).

Stacktrace:

swagger-ui-bundle.js:67 Unhandled promise rejection Error: Zone.js has detected that ZoneAwarePromise `(window|global).Promise` has been overwritten.
Most likely cause is that a Promise polyfill has been loaded after Zone.js (Polyfilling Promise api is not necessary when zone.js is loaded. If you must load one, do so before loading zone.js.)
    at Function.webpackJsonp.../../../../zone.js/dist/zone.js.Zone.assertZonePatched (zone.js:44)
    at new NgZone (core.es5.js:3775)
    at PlatformRef_.webpackJsonp.../../../core/@angular/core.es5.js.PlatformRef_._bootstrapModuleFactoryWithZone (core.es5.js:4492)
    at core.es5.js:4537
    at swagger-ui-bundle.js:67
    at swagger-ui-bundle.js:67
    at MutationObserver.f (swagger-ui-bundle.js:67)
    at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:391)
    at Zone.webpackJsonp.../../../../zone.js/dist/zone.

Please check repository created to reproduce an issue: https://github.com/asakalou/swagger-angular4-issue

Please check swagger component at https://github.com/asakalou/swagger-angular4-issue/blob/master/src/app/swagger/swagger.component.ts

Q A
Bug or feature request? Bug
Which Swagger/OpenAPI version?
Which Swagger-UI version? [email protected]
How did you install Swagger-UI? via npm
Which broswer & version? Chrome Version 60.0.3112.90 (Official Build) (64-bit)
Which operating system? macOS Sierra 10.12.6

Configuration (browser query string, constructor, config.yaml)

http://petstore.swagger.io/v2/swagger.json

Expected Behavior

No error, should render swagger ui.

Current Behavior

Error during initializing SwaggerUIBundle inside angular4 application.

Context

We are trying to render swagger ui inside our application to provide customers an interface for our API access.

asakalou avatar Aug 17 '17 08:08 asakalou

This is interesting - the Promise polyfill we use includes a test to prevent an equivalent Promise implementation from being overwritten.

core-js (the polyfill module we use) had some discussion of this: https://github.com/zloirock/core-js/issues/283.

It's possible that the Zone Promise isn't similar enough to the official ES6 Promise specification, so the polyfill overwrites it. A possible solution, in that case, would be to only apply our polyfill if window.Promise doesn't exist at all.

Thanks for the example repository! It will help a lot with debugging this.

shockey avatar Aug 17 '17 17:08 shockey

You are welcome!

asakalou avatar Aug 18 '17 14:08 asakalou

Hello @asakalou, I found a solution if you want to integrate swagger-ui on Angular 4. (Thanks to @shockey for your comment)

Firstly, go to polyfills.ts and add this before the import of zone.js :

import {SwaggerUIBundle, SwaggerUIStandalonePreset} from 'swagger-ui-dist';

export const swaggerUIBundle = SwaggerUIBundle;
export const swaggerUIStandalonePreset = SwaggerUIStandalonePreset;`

Then, go to your swagger.component.ts and use the const exported like this :

import { swaggerUIBundle, swaggerUIStandalonePreset } from '../../polyfills';

ngAfterViewInit() {
    const ui = swaggerUIBundle({
      url: 'http://petstore.swagger.io/v2/swagger.json',
      domNode: this.el.nativeElement.querySelector('.swagger-container'),
      deepLinking: true,
      presets: [
        swaggerUIBundle.presets.apis,
        swaggerUIStandalonePreset
      ],
      plugins: [
        swaggerUIBundle.plugins.DownloadUrl
      ],
      layout: 'StandaloneLayout'
    });
}

Finally, add the CSS of Swagger UI in .angular-cli.json :

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

lauthieb avatar Aug 25 '17 07:08 lauthieb

Thanks for the workaround, @lauthieb!

It’s worth noting that this is (was?) being discussed on Zone’s side, which IMO would be the most correct place to fix this: https://github.com/angular/zone.js/issues/783

shockey avatar Aug 25 '17 07:08 shockey

@lauthieb, it works, thank you!

asakalou avatar Aug 25 '17 10:08 asakalou

Hi everyone, I just fixed this in a PR.

Basically, I changed our internal polyfill to only take effect when there's no Promise implementation at all (see the diff here).

It's a naive solution, but it should work well for this use case. The fix should go live tonight when we do our weekly release.

Thanks @asakalou & @lauthieb! Please let me know if there are any lingering issues with this.

shockey avatar Aug 25 '17 23:08 shockey

Hi all,

Is @lauthieb 's solution to using swagger-UI in an angular app, still the best way to do this? Asking as an angular novice.

Thanks.

mckennajones avatar Mar 05 '18 23:03 mckennajones

Got this working in my angular app, but the CSS isn't quite working properly as you can see in this screenshot.

swaggeruicssissue

As you can see everything is right justified, the authorize lock is missing, and the carrot for expanding the section is also missing. Any ideas @lauthieb or @asakalou ? Did you run into this issue?

Thanks

mckennajones avatar Mar 08 '18 20:03 mckennajones

Got the same CSS issue as mckennajones. Everthing is working fine except the class="col respones-col_description"

solved it by removin bootstrap from the styles in the angular-cli.json

  "styles": [
    "../node_modules/swagger-ui-dist/swagger-ui.css",
    "../node_modules/bootstrap/dist/css/bootstrap.min.css",   
    "../node_modules/font-awesome/css/font-awesome.css",
    "styles.css"
  ]

But now I come up with a new Question, because I ran into other issues. My best solution for now is importing bootstrap in the index.html

What is the propper way to use Bootstrap with swagger-ui?

Brentei avatar Mar 20 '18 13:03 Brentei

Hey @Brentei,

My solution to the CSS issue was to use angular's View Encapsulation feature. Most browsers don't yet support Native encapsulation, but Emulated worked OK for me in this scenario.

So in my Swagger component's CSS file I imported the swagger CSS: @import "~swagger-ui/dist/swagger-ui.css

And in my component that uses bootstrap: @import "~bootstrap/dist/css/bootstrap.min.css";

This obviously isn't a great solution if you want to use bootstrap in multiple components, but it worked for me.

mckennajones avatar Mar 20 '18 16:03 mckennajones

I would also recommend against using the swagger-ui-dist package in Angular. It causes you bundle sizes to be much larger than they need to be. I was able to use the normal swagger-ui package in an Angular 5 project by doing a simple const SwaggerUI = require("swagger-ui"); in my swagger component. For more info, check out this issue

mckennajones avatar Mar 20 '18 17:03 mckennajones

Hey @mckennajones

Thank you very much, as my testing was successfull, I will rebuild my app also to use the swagger-ui instead of the swagger-ui-dist. And also thanks for the css tip, its working fine too :)

I used a differnt approach as I collect my docs and store them in a DB.

import { Component, OnInit, Input, ViewChild, ElementRef, } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Location } from '@angular/common';
import { HttpClient } from '@angular/common/http';

import SwaggerUI from "swagger-ui"


import { Swagger } from '../swagger';
import { SwaggerService } from '../swagger.service';
import { Observable } from 'rxjs/Observable';

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

  swagger: Swagger;

  constructor(
    private el: ElementRef,
    private swaggerService: SwaggerService,
    private location: Location,
    private route: ActivatedRoute
  ){};


ngOnInit() {
    this.getSwagger();
  }

  getSwagger(): any {
     const _id = this.route.snapshot.paramMap.get('_id');
      this.swaggerService.getSwagger(_id).subscribe(
        swagger => {
          console.log(swagger);
          this.swagger = swagger;
          this.createSwaggerView();
        }
      );
  }

  createSwaggerView(): void {
   const swagDoc = this.swagger[0].data;
   const ui = SwaggerUI({
     spec: swagDoc,
     domNode: this.el.nativeElement.querySelector('.swagger-test-container'),
     deepLinking: true,
     presets: [
       SwaggerUI.presets.apis
     ],
   });
 }
ngOnInit() {
    this.getSwagger();
  }

  getSwagger(): any {
     const _id = this.route.snapshot.paramMap.get('_id');
      this.swaggerService.getSwagger(_id).subscribe(
        swagger => {
          console.log(swagger);
          this.swagger = swagger;
          this.createSwaggerView();
        }
      );
  }

  createSwaggerView(): void {
   const swagDoc = this.swagger[0].data;
   const ui = SwaggerUI({
     spec: swagDoc,
     domNode: this.el.nativeElement.querySelector('.swagger-test-container'),
     deepLinking: true,
     presets: [
       SwaggerUI.presets.apis
     ],
   });
 }

Brentei avatar Mar 29 '18 08:03 Brentei

I was trying to implement Swagger UI with angular6 but am getting error TypeError: Right-hand side of 'instanceof' is not callable

image

ravind996 avatar Aug 09 '18 06:08 ravind996

Below swagger-component.ts code is working fine in Angular 4, But it is getting error in Angular 6 ERROR TypeError: Right-hand side of 'instanceof' is not callable

Any root cause to resolve this issues.....

ngAfterViewInit() { const ui = SwaggerUI({ url: 'http://petstore.swagger.io/v2/swagger.json', domNode: this.el.nativeElement.querySelector('.swagger-container'), deepLinking: true, presets: [ SwaggerUI.presets.apis ], }); }

ravind996 avatar Aug 09 '18 08:08 ravind996

@mckennajones Perhaps you solved the column width issue. I solved it using a CSS-hack:

#swagger-container .col {
  width: 0;
}

nekman avatar Aug 29 '18 07:08 nekman

@ravind996 , I have the same issues with anuglar6, did you manage to find a solution?

ricogu avatar Nov 07 '18 17:11 ricogu

If you're still having problems, please open a new issue 😄

shockey avatar Nov 12 '18 14:11 shockey