Tengo un archivo JavaScript llamado abc.js que tiene una función 'pública' llamada xyz() . Quiero llamar a esa función en mi proyecto Angular. ¿Cómo puedo hacer eso?
Consulte los scripts dentro del angular-cli.json ( angular.json cuando se usa angular 6+).
"scripts": [ "../path" ]; luego agregue en typings.d.ts (cree este archivo en src si aún no existe)
declare var variableName:any;Importarlo en su archivo como
import * as variable from 'variableName';Para incluir una biblioteca global, por ejemplo, el archivo jquery.js en la matriz de scripts de angular-cli.json ( angular.json cuando se usa angular 6+):
"scripts": [ "../node_modules/jquery/dist/jquery.js" ]Después de esto, reinicie ng serve si ya se inició.
Agregue un archivo js externo en index.html .
<script src="./assets/vendors/myjs.js"></script>Aquí está el archivo myjs.js :
var myExtObject = (function() { return { func1: function() { alert('function 1 called'); }, func2: function() { alert('function 2 called'); } } })(myExtObject||{}) var webGlObject = (function() { return { init: function() { alert('webGlObject initialized'); } } })(webGlObject||{})Luego declara que está en un componente como el siguiente
demo.component.ts
declare var myExtObject: any; declare var webGlObject: any; constructor(){ webGlObject.init(); } callFunction1() { myExtObject.func1(); } callFunction2() { myExtObject.func2(); }demostración.componente.html
<div> <p>click below buttons for function call</p> <button (click)="callFunction1()">Call Function 1</button> <button (click)="callFunction2()">Call Function 2</button> </div>me esta funcionando...