首页 > 解决方案 > Angular:无法将值传递给 javascript (.js) 文件

问题描述

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

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

现在进行第 3 步,

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

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

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

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

包.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 个变量的函数。我怎样才能做到这一点?

标签: javascriptnode.jsangulartypescriptangular-components

解决方案


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

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

现在在 Angular 组件中导入这个 js 文件 现在将文件导入到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 文件中可以导入任何组件并使用它


推荐阅读