Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

210
Visualizações
Import JavaScript object from external file in Angular2 Component

I am trying to use SwaggerUI in an angular2 project with TypeScript. SwaggerUI doesn't see to have TypeScript definitions.So I am trying to use the JavaScript file.

This project is created using ASP.Net Core SPA Services template. I have added all the SwaggerUI files from "dist" folder to "wwwroot" folder in my project.

I have referenced the JavaScript file of SwaggerUI from the "wwwroot" folder of my project in the _Layout.cshtml (view page) just like normal javascript file and trying to use ShaggerUIBundle object.

_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;
}

Now SwaggerUIBundle is populated with the object that I am expecting. But I am not able to use this anywhere in the component.

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 is always null.

I think this is because of the fact that no value is actually assigned to SwaggerUIBundle, though it has populated with an object.

SwaggerUIBundle is a function. I tried multiple ways to assign this function as suggested here and here.

I tried to import instead of referencing the file.

import SwaggerUIBundle from 'path from root of the app'

As the "wwwroot" folder is a virtual folder, that represents root folder of the application, when I try to import using "import" TypeScript compiler throws an error that it can't find the file.

Then I moved all SwaggerUI related files to the respective angular component folder and tried importing from there. Then I get this error.

'allowJs is not set.

I have added 'allowJs' to tsconfig. Still the error wont go away.

"compilerOptions": {
    "moduleResolution": "node",
    "target": "es5",
    "sourceMap": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "skipDefaultLibCheck": true,
    "lib": [ "es6", "dom" ],
    "types": [ "node" ],
    "allowJs": true
  }

Any help is appreciated.

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

this refers to an instance of the enclosing class, not lexical environment of the module that defines the class.

Instead of using this import and refer to SwaggerUIBundle directly as in

import SwaggerUIBundle from 'path/to/swagger-ui/dist/bundle.js';

Additionally, instead of initializing it in ngOnInit, a per component lifecycle event, you likely want to do it once

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"
});

This sort of logic should be extracted into a dedicated function or a service in order to keep your views clean.

over 4 years ago · Santiago Trujillo Relatório

0

Try the below method to include the javascript file,

component.ts

@Component({
selector: 'test',
template: `
    <div class="row">
      Loading...
    </div>
    `,
styles: []
})
export class TestComponent {

public ngOnInit() {
    // Pass js file path
    this.loadScript('src/assets/js/myCropper.js');       
}

public loadScript(url) {
    console.log('preparing to load...')
    let js = document.createElement('script');
    js.src = url;
    js.type = 'text/javascript';
    document.getElementsByTagName('head')[0].appendChild(node);
 }
}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda