How to get a variable in external file js and use it in angular cli?

0

Good I have the doubt as I can use for example a variable declared in js in an external file and use it in angular cli example:

@angular/cli: 1.7.4
@angular-devkit/build-optimizer: 0.3.2
@angular-devkit/core: 0.3.2
@angular-devkit/schematics: 0.3.2
@ngtools/json-schema: 1.2.0
@ngtools/webpack: 1.10.2
@schematics/angular: 0.3.2
@schematics/package-update: 0.3.2
typescript: 2.5.3
webpack: 3.11.0

archivo.js

function myFunction(){
  var variable
}

communicate with componente.component.ts

I was seeing many answers for example in the component file import something like this

 import * as xJS from '../../../assets/js/archivo.js';

to use it but it does not work the component file is in another external folder.

Would you like to know if there is a way? just call it or call the function for example import variable from "archivo.js" or function

    
asked by Chuy Roldan 02.07.2018 в 18:59
source

1 answer

1

The external file has to EXPORT the variable or function that you want to IMPORT.

In file.js

export var variable = 'variable que se exporta'

export function myFunction() {
   var variable
   return variable // O lo que quieras hacer con tu funcion :D
}

In your componente.component.ts you can import it:

import * as xJS from '../../../assets/js/archivo.js';

@Component({
  selector: 'app-root',
  templateUrl: './componente.component.html',
  styleUrls: ['./componente.component.scss']
})
export class ComponenteComponent {
  constructor() {
    console.log(xJS.variable);
    console.log(xJS.myFunction());
  }

Or you can do

import { variable, myFunction } from '../../../assets/js/archivo.js';
@Component({
      selector: 'app-root',
      templateUrl: './componente.component.html',
      styleUrls: ['./componente.component.scss']
    })
    export class ComponenteComponent {
      constructor() {
        console.log(variable);
        console.log(myFunction());
    }
    
answered by 02.07.2018 / 20:02
source