How to use javascript functions in an Angular 2 component from a different file

后端 未结 4 1561
后悔当初
后悔当初 2020-12-15 20:14

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 fi

相关标签:
4条回答
  • 2020-12-15 20:41

    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.

    0 讨论(0)
  • 2020-12-15 20:43

    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.

    0 讨论(0)
  • 2020-12-15 20:53

    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';
    
    0 讨论(0)
  • 2020-12-15 20:55

    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

    0 讨论(0)
提交回复
热议问题