angular2使用外部javascript文件

angular2使用外部javascript文件,javascript,angular,html5-canvas,Javascript,Angular,Html5 Canvas,我想把我用纯javascript和html5制作的在线游戏放到我的angular2项目中。 我在外部文件中编写了脚本,并在angularindex.html的头部添加了脚本标记,在我的组件的typescript中,我声明了我的onload函数,如下所示: declare var startGame1: any; Unhandled Promise rejection: Error in :0:0 caused by: Cannot read property 'clearRect' of un

我想把我用纯javascript和html5制作的在线游戏放到我的angular2项目中。
我在外部文件中编写了脚本,并在angular
index.html
的头部添加了脚本标记,在我的组件的typescript中,我声明了我的onload函数,如下所示:

declare var startGame1: any;
Unhandled Promise rejection: Error in :0:0 caused by: Cannot read property 'clearRect' of undefined ; Zone: angular ; Task: Promise.then ; Value:
ViewWrappedError {__zone_symbol__error: Error: Error in :0:0 caused by: Cannot read property 'clearRect' of undefined at ViewWrappedErro……} Error: Error in :0:0 caused by: Cannot read property 'clearRect' of undefined
startGame1是一种让画布为我的游戏做好准备的方法。
问题是,当我在
AfterViewInit
中调用
startGame1()
时,会出现如下错误:

declare var startGame1: any;
Unhandled Promise rejection: Error in :0:0 caused by: Cannot read property 'clearRect' of undefined ; Zone: angular ; Task: Promise.then ; Value:
ViewWrappedError {__zone_symbol__error: Error: Error in :0:0 caused by: Cannot read property 'clearRect' of undefined at ViewWrappedErro……} Error: Error in :0:0 caused by: Cannot read property 'clearRect' of undefined

我建议您使用
.angular cli.json
加载外部js

apps->scripts
中,在数组中插入外部
.js
的相对路径

app
文件夹中,创建一个
.d.ts
文件,插入您的
声明var startGame1:any。例如:

myGame.d.ts

declare var startGame1: any;

网页包将自动加载
myGame.d.ts
,然后为你的应用程序定义你的
startGame1

你使用angular cli吗?是的,我使用@Giovane