Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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';

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.6k users

...