javascript - Angular:无法将值传递给 javascript (.js) 文件
问题描述
- 假设我在 test1.js 中有一个 add(int x, int y) 函数
- 从角度,我将获得用户输入(int x,int y)
- 现在我需要将x和y传递给test1.js并使用这两个变量在 in 中调用 add add 函数,并在任何组件的 .ts 中返回结果
我已经完成了第 1 步和第 2 步。
现在进行第 3 步,
a)如何将 app.component.ts 中的 2 个值发送到该 .js 文件?
b)如何使用特定的x和y调用该 .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 个变量的函数。我怎样才能做到这一点?
解决方案
创建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 文件中可以导入任何组件并使用它
推荐阅读
- vhdl - 倒数无符号数时每 10 个都缺少 9 和 8
- ios - 如何使用 Firebase 存储中的图像填充 UICollectionView 单元格?
- python - 使用 ax.text,matplotlib 相对于轴定位字体
- batch-file - 批处理调用管理批处理,变量不交叉
- python - 是否可以使用 C# 和 Python 创建桌面应用程序来创建现代 GUI
- python - 如何在 Python Seaborn 的线图中的每个标记上添加值/标签?
- javascript - 如何创建检查 div 元素样式的事件侦听器?
- python - Python Dataframe 将数据框列表的列表转换为单个数据框
- c - 我的函数返回分段错误错误,显然没有错
- javascript - 是否可以在 Blazor 的 DOM 事件中混合使用 Javascript 和 C# 代码?