Eu tenho um arquivo JavaScript chamado abc.jsque tem uma função 'pública' chamada xyz(). Quero chamar essa função no meu projeto Angular. Como faço isso?
Eu tenho um arquivo JavaScript chamado abc.jsque tem uma função 'pública' chamada xyz(). Quero chamar essa função no meu projeto Angular. Como faço isso?
Respostas:
Consulte os scripts dentro do arquivo angular-cli.json( angular.jsonao usar angular 6+).
"scripts": [
"../path"
];
em seguida, adicione typings.d.ts(crie este arquivo srcse ele ainda não existir)
declare var variableName:any;
Importe-o em seu arquivo como
import * as variable from 'variableName';
plunkerpara reproduzir
Para incluir uma biblioteca global, por exemplo, jquery.jsarquivo na matriz de scripts angular-cli.json( angular.jsonao usar o angular 6+):
"scripts": [
"../node_modules/jquery/dist/jquery.js"
]
Depois disso, reinicie o serviço se já estiver iniciado.
declare var $: any;
Adicione o arquivo js externo em index.html .
<script src="./assets/vendors/myjs.js"></script>
Este é o arquivo 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||{})
Em seguida, declare que está em um componente como abaixo
demo.component.ts
declare var myExtObject: any;
declare var webGlObject: any;
constructor(){
webGlObject.init();
}
callFunction1() {
myExtObject.func1();
}
callFunction2() {
myExtObject.func2();
}
demo.component.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>
Está funcionando para mim ...
declaresignifica - essencialmente " declareé usado para dizer ao TypeScript que a variável foi criada em outro lugar " (a partir desta resposta ).
Você também pode
import * as abc from './abc';
abc.xyz();
ou
import { xyz } from './abc';
xyz()