我试图在带有TypeScript的angular2项目中使用SwaggerUI。 SwaggerUI没有看到TypeScript定义。所以我试图使用JavaScript文件。
此项目是使用ASP.Net Core SPA服务模板创建的。我已将“dist”文件夹中的所有SwaggerUI文件添加到项目中的“wwwroot”文件夹中。
我在_Layout.cshtml(查看页面)中的项目的“wwwroot”文件夹中引用了SwaggerUI的JavaScript文件,就像普通的javascript文件一样,并尝试使用ShaggerUIBundle对象。
_Layout.cshtml
<script src="/swagger-ui/swagger-ui-bundle.js"> </script>
<script src="/swagger-ui/swagger-ui-standalone-preset.js"> </script>
Swagger.Component.ts
//my import statements
export class SwaggerComponent implements OnInit {
SwaggerUIBundle:any;
}
现在,SwaggerUIBundle会填充我期待的对象。但我无法在组件中的任何位置使用它。
ngOnInit(): void {
(<any>window).ui = this.SwaggerUIBundle({
url: "<url>",
dom_id: '#swagger-ui',
presets: [
this.SwaggerUIBundle.presets.apis
],
plugins: [
this.SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout"
})
}
this.SwaggerUIBundle始终为空。
我认为这是因为实际上没有为SwaggerUIBundle分配任何值,尽管它已经填充了一个对象。
SwaggerUIBundle是一个功能。我尝试了多种方法来按照建议here和here分配此功能。
我尝试导入而不是引用该文件。
import SwaggerUIBundle from 'path from root of the app'
由于“wwwroot”文件夹是一个虚拟文件夹,它代表应用程序的根文件夹,当我尝试使用“import”导入时,TypeScript编译器会抛出一个无法找到文件的错误。
然后我将所有SwaggerUI相关文件移动到相应的角度组件文件夹并尝试从那里导入。然后我收到了这个错误。
'allowJs未设置。
我在tsconfig中添加了'allowJs'。这个错误仍然不会消失。
"compilerOptions": {
"moduleResolution": "node",
"target": "es5",
"sourceMap": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"skipDefaultLibCheck": true,
"lib": [ "es6", "dom" ],
"types": [ "node" ],
"allowJs": true
}
感谢任何帮助。
答案 0 :(得分:0)
this
指的是封闭类的实例,而不是定义类的模块的词法环境。
而不是使用this
导入,而是直接引用SwaggerUIBundle
,如
import SwaggerUIBundle from 'path/to/swagger-ui/dist/bundle.js';
此外,不是在ngOnInit
中初始化每个组件生命周期事件,您可能希望这样做一次
import SwaggerUIBundle from 'path/to/swagger-ui/dist/bundle.js';
SwaggerUIBundle({
url: "<url>",
dom_id: '#swagger-ui',
presets: [
SwaggerUIBundle.presets.apis
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout"
});
这种逻辑应该被提取到专用函数或服务中,以保持您的视图清洁。
答案 1 :(得分:0)
尝试使用以下方法添加javascript文件
component.ts
Sql