How to use javascript functions in an Angular 2 co

2020-02-09 07:24发布

问题:

I have a javascript file that contains some data manipulation functions (No DOM manipulation at all) such as float rounding, mathematical operations, ...etc

my js file called myexample.js looks like that

function example(input) {
  return input * 2
}
module.exports = { example: example }

and then I have my angular component example.component.ts

for example:

import { Component, EventEmitter} from '@angular/core';
@Component({
  selector: 'input-number',
  template: `<input 
              type='text' 
              [(value)]='value' 
              (blur)='runExample()' 
             />`,
  inputs: ['value'],
  outputs: ['valueChange']
})
export class Example {
  value: string;
  valueChange = new EventEmitter;

  runExample() {
    let val = parseFloat(this.value);
    // here i need to call example(input) from myexample.js
    // and assign the return to val
    this.valueChange.emit(val);
  }

I have been searching for quite a while now and tried multiple things but unfortunately with no luck at all.

I would be really grateful if someone can help.

回答1:

You can export functions in TypeScript:

export function example(input) {
  return input * 2;
}

and use it this way (assuming your file name is lib.ts):

import {example} from './lib';

example();

If you want to use a CommonJS file, you need to configure SystemJS in the map attribute:

System.config({
  (...)
  map: {
    lib: 'path/to/lib/js'
  }
});

You can import your module the same way then:

import {example} from './lib';


回答2:

this is what it worked for me I was trying to use html2pdf from an Angular2 app, so I had to make a reference to this function

var html2pdf = (function(html2canvas, jsPDF) {

declared in html2pdf.js.

So I added just after the import declarations in my angular-controller this declaration:

declare function html2pdf(html2canvas, jsPDF): any;

then, from a method of my angular controller I'm calling this function:

generate_pdf(){
    this.someService.loadContent().subscribe(
      pdfContent => {
        html2pdf(pdfContent, {
          margin:       1,
          filename:     'myfile.pdf',
          image:        { type: 'jpeg', quality: 0.98 },
          html2canvas:  { dpi: 192, letterRendering: true },
          jsPDF:        { unit: 'in', format: 'A4', orientation: 'portrait' }
        });
      }
    );
  }

Hope it helps



回答3:

Another way is to add your js functions defined in a separate file to a global scope. So in your js file you can add sth like this:

$(document).ready(function() {
    window.example = example;
}

Then in your component typeScript file, right below the imports, you can declare this function:

declare function example(input): void;

And then you can just simply use this function in the component methods.



回答4:

I finally found out the answer; it was to basically make a typings file and add it to the project.

The problem was related to TypeScript not Angular2. In typeScript you can't simply use any JS file without having a definition (typing) file that declares the types of the vars, the params of the functions, as well as the returns. check this link to know how to create one.