如何从其他文件使用Angular 2组件中的javascript函数 [英] How to use javascript functions in an Angular 2 component from a different file

查看:65
本文介绍了如何从其他文件使用Angular 2组件中的javascript函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我的名为 myexample.js 的js文件看起来像这样

my js file called myexample.js looks like that

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

然后我有我的角度分量 example.component.ts

and then I have my angular component 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);
  }

我已经搜索了很长一段时间,尝试了多种尝试,但不幸的是根本没有运气.

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.

推荐答案

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

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

该问题与TypeScript无关,而不是与Angular2有关.在typeScript中,如果没有定义(类型化)文件来声明vars的类型,函数的参数以及返回值,就不能简单地使用任何JS文件.检查此链接以了解如何创建链接.

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.

这篇关于如何从其他文件使用Angular 2组件中的javascript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆