我参考了许多关于堆栈溢出的文章,以调用Angular6的typescript中的JavaScript方法,但它们都不起作用,首先我寻找一个简单的函数与警报将在JavaScript中执行并从typescript调用,请求一个工作方法和如何创建JavaScript文件的d.ts文件的详细描述,以及所有配置文件中的详细更改,如angular.json,tsconfig.json等,如果可能,请发布Angular6的工作和测试示例
发布于 2019-02-05 00:35:34
转到angular.json或angular-cli.json(对于angular 4项目),并添加一个脚本标记来引用外部javascript文件,假设demo.js如下所示
"scripts":[
"./assets/demo.js"
]
转到tsconfig.json并添加"allowJS“作为true,如下所示
"allowJS":true
将外部js文件添加到assets文件夹中,让我们称其为demo.js
在app文件夹下,为外部js文件组件的类型声明添加appcomponent.d.ts
在appcomponent.html中创建一个将命中ts方法的按钮,并从javascript调用js方法。
<div>
<button (click)="calljsfunction()"> call external JS file</button>
</div>
在ts文件内部实现calljsfunction(),该函数将从javascript调用js方法,如下所示
export class AppComponent{
calljsfunction(){
console.log("inside ts file method");
var p1 = new Gemoetry.point(1,0)
}
}
在app.component.d.ts中实现d.ts
declare module MGeometry{
export interface Point{
x:number;
y:number;
new (x:number,y:number):Point;
}
export interface Line{
point1:Point;
point2:Point;
new (p1:Point,p2:Point):Point;
}
export interface Main{
point: Point;
line : Line;
}
}
declare var Geometry:MGeometry.Main;
在demo.js中
line : (function(){
function line(p1,p2){
this.point1 = {x: p1.x, y: p1.y};
this.point2 = {x: p2.x, y: p2.y};
}
return line;
} ) (),
在类似的代码行上实现demo.js文件中的点函数
发布于 2018-09-23 06:05:06
如果它是一个像moment这样的NPM包,那么你可以安装NPM并像这样引用它
import * as moment from 'moment';
然后像使用任何其他对象一样使用它
moment('dateStringToParse');
如果你想添加非NPM脚本,那么将这些文件放在你的JavaScript文件夹中,并将它们包含在你的angular cli json文件的“script”:[]部分中。
发布于 2018-09-23 06:15:23
我认为有很多实用工具可以为Angular6创建脚手架项目模板。其中最好的是angular-cli。
另外,请确保您的计算机中安装了node。节点安装完成后,使用"npm install -g @angular/cli“。对于mac/linux,请在命令前使用"sudo“。
得到确认后,创建一个项目文件所在的目录,然后在该目录中输入"cd“。输入"ng new“。这将花费几分钟来加载所有依赖项以及"TypeScript“和"WebPack”的配置。Angular cli将隐藏webpack文件的配置,但它在构建项目时会使用此配置。
最后使用"ng serve“查看angular是否正常运行。
angular cli的优势在于,它在开发代码时提供了最佳实践。我在我的一个SharePoint项目中使用它来构建购物车,并且非常喜欢它。
您还可以通过单击以下链接查看官方文档:https://cli.angular.io/
编码快乐!!
https://stackoverflow.com/questions/52459463
复制相似问题