角度:无法将值传递给javascript(.js)文件

时间:2020-04-20 13:52:01

标签: javascript node.js angular typescript angular-components

  1. 让我说我在test1.js中有一个add(int x,int y)函数
  2. 从角度,我将获得用户输入(int x,int y)
  3. 现在我需要将 x y 传递给 test1.js ,并使用这2个变量调用内部的add add函数,并获取结果返回到任何组件的.ts

我已经完成了第1步和第2步。

现在进入第3步,

a)如何将2个值从app.component.ts发送到该.js文件?

b)如何使用特定的 x y 调用该.js文件中编写的函数?

[我的意思是我知道如何在.js中调用功能,但是现在我必须从具有值的.ts文件中执行此操作]

从这里我正在运行我的.js文件

package.json

{
  "name": "rest-test3",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "runServer": "node test1.js"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~9.1.0",
    "@angular/common": "~9.1.0",
    "@angular/compiler": "~9.1.0",
    "@angular/core": "~9.1.0",
    "@angular/forms": "~9.1.0",
    "@angular/platform-browser": "~9.1.0",
    "@angular/platform-browser-dynamic": "~9.1.0",
    "@angular/router": "~9.1.0",
    "express": "^4.17.1",
    "install": "^0.13.0",
    "pg": "^8.0.2",
    "rxjs": "~6.5.4",
    "tslib": "^1.10.0",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.901.0",
    "@angular/cli": "~9.1.0",
    "@angular/compiler-cli": "~9.1.0",
    "@angular/language-service": "~9.1.0",
    "@types/node": "^12.11.1",
    "@types/jasmine": "~3.5.0",
    "@types/jasminewd2": "~2.0.3",
    "codelyzer": "^5.1.2",
    "jasmine-core": "~3.5.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.4.1",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage-istanbul-reporter": "~2.1.0",
    "karma-jasmine": "~3.0.1",
    "karma-jasmine-html-reporter": "^1.4.2",
    "protractor": "~5.4.3",
    "ts-node": "~8.3.0",
    "tslint": "~6.1.0",
    "typescript": "~3.8.3"
  }
}

您可以在脚本中看到我有runServer变量来调用.js文件。现在,我需要在此文件中使用2个变量调用一个函数。我该怎么办?

1 个答案:

答案 0 :(得分:0)

创建test.js并将其放在/src/assets

    export const add = function (x, y) {
      return x+y;
    }

现在将这个js文件导入Angular组件中 现在将文件导入app.component.ts

import { Component } from '@angular/core';
import { add } from '../assets/myjs.js'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'hallbooking-app';
  constructor() {
    const total = add(5,10);
    console.log(total);
  }

}

现在您可以将js文件中的任何组件导入并使用它