如何在不同文件的Angular 2组件中使用javascript函数

Mos*_*een 16 typescript angular

我有一个javascript文件,其中包含一些数据操作函数(根本没有DOM操作),例如浮点舍入,数学运算,等等

我的js文件名为myexample.js就是这样

function example(input) {
  return input * 2
}
module.exports = { example: example }
Run Code Online (Sandbox Code Playgroud)

然后我有我的角度组件example.component.ts

例如:

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);
  }
Run Code Online (Sandbox Code Playgroud)

我现在已经搜索了很长一段时间并试了很多东西,但遗憾的是没有运气.

如果有人可以提供帮助,我将非常感激.

Thi*_*ier 17

您可以在TypeScript中导出函数:

export function example(input) {
  return input * 2;
}
Run Code Online (Sandbox Code Playgroud)

并以这种方式使用它(假设您的文件名是lib.ts):

import {example} from './lib';

example();
Run Code Online (Sandbox Code Playgroud)

如果要使用CommonJS文件,则需要在map属性中配置SystemJS :

System.config({
  (...)
  map: {
    lib: 'path/to/lib/js'
  }
});
Run Code Online (Sandbox Code Playgroud)

您可以使用相同的方式导入模块:

import {example} from './lib';
Run Code Online (Sandbox Code Playgroud)


Mos*_*een -1

我终于找到了答案;基本上是创建一个打字文件并将其添加到项目中。

该问题与 TypeScript 相关,而不是 Angular2。在 typeScript 中,如果没有声明变量类型、函数参数以及返回值的定义(键入)文件,则不能简单地使用任何 JS 文件。检查此链接以了解如何创建一个。

  • 你到底是怎么做到的? (8认同)
  • 请解释您找到的解决方案的步骤。 (7认同)