在Angular项目中添加Swagger UI的解决方法如下:
首先,确保已经安装了Node.js和Angular CLI。
创建一个新的Angular项目。打开终端并执行以下命令:
ng new swagger-ui-example
进入项目目录:
cd swagger-ui-example
安装Swagger UI库。在终端中执行以下命令:
npm install swagger-ui-dist
创建一个新的组件来显示Swagger UI。在终端中执行以下命令:
ng generate component swagger-ui
打开src/app/swagger-ui/swagger-ui.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({
url: 'http://petstore.swagger.io/v2/swagger.json',
dom_id: '#swagger-ui',
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIBundle.SwaggerUIStandalonePreset
],
layout: 'BaseLayout'
});
}
}
打开src/app/swagger-ui/swagger-ui.component.html
文件,并添加以下代码:
打开src/app/app.module.ts
文件,并将SwaggerUiComponent
添加到declarations
和imports
数组中:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { SwaggerUiComponent } from './swagger-ui/swagger-ui.component';
@NgModule({
declarations: [
AppComponent,
SwaggerUiComponent
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
打开src/app/app.component.html
文件,并在
的下方添加以下代码:
启动开发服务器。在终端中执行以下命令:
ng serve
打开浏览器,并访问http://localhost:4200
。你将看到Swagger UI界面,展示了来自http://petstore.swagger.io/v2/swagger.json
的Swagger文档。
这样,你就成功地在Angular项目中添加了Swagger UI。你可以根据自己的需要,修改Swagger UI配置和URL。