Adding the Swagger Editor to an Angular project

2020-07-10 03:38发布

问题:

I want to insert the Swagger UI and Swagger Editor into my Angular project. So that it will look like this: http://editor.swagger.io/?docExpansion=none

Thanks to the following instructions I was already able to add the Swagger UI to my Angular project: https://github.com/agoncal/swagger-ui-angular6

What is still missing is the Swagger Editor where the user can edit the OpenAPI Specification (see left side of the first link).

The target state of my application should be that the OpenAPI Specification is loaded and the user then has a visual overview of the API and should also be able to edit this API via the Swagger editor (missing part). So pretty much the functionality of the first link.

So my question is, how can I implement the Swagger Editor to my Angular project? I didn't find any information about it on the internet.

回答1:

You can use swagger-editor-dist package to achieve this.

npm i swagger-editor-dist --save

After you install the dependency, you have to include the required scripts and css file. You can do that in angular.json file

"styles": [
   "node_modules/swagger-editor-dist/swagger-editor.css",
   "src/styles.css"
 ],
"scripts": [
   "node_modules/swagger-editor-dist/swagger-editor-bundle.js",
   "node_modules/swagger-editor-dist/swagger-editor-standalone-preset.js"
 ]

Next step is to prepare the html where you want to put the editor. Pick any of your components and add

<div id="swagger-editor"></div>

Final step is to instantiate the editor to that div. In the same component, add this

declare const SwaggerEditorBundle: any;
declare const SwaggerEditorStandalonePreset: any;
....
....
ngOnInit(): void {
  const editor = SwaggerEditorBundle({
    dom_id: '#swagger-editor',
    layout: 'StandaloneLayout',
    presets: [
      SwaggerEditorStandalonePreset
    ],
    url: 'http://rackerlabs.github.io/wadl2swagger/openstack/swagger/dbaas.json'
  });
}

I also created an example app for this.

Feel free to checkout my Github Repo - Swagger Editor Angular 8