gpt4 book ai didi

angular - 如何在 ionic 3 中包含 JS 文件

转载 作者:太空狗 更新时间:2023-10-29 16:54:56 24 4
gpt4 key购买 nike

我正在寻找一种从我包含在 Assets /数据文件夹中的外部 js 文件访问变量的方法

下面是我试过的

放置 test.js assets/data 文件夹

test.js 添加变量 testvar = "heloo from external js";

src/index.html中添加脚本标签<script src="assets/data/test.js"></script>

app.component.ts我在导入后添加了这一行; declare var testvar: any;

在构造函数中添加了这一行来记录值 console.log(testvar);

结果是error:ERROR ReferenceError: testvar is not defined

那么,我如何在 typescript 中使用我的 js 变量?

最佳答案

这个解决方案只对我有用

Put the import js in src/index.html header tag, before the build/polyfills.js and build/main.js (they are in body tag);

示例:我使用 var testvar 创建了一个文件 src/assets/test.js,导入到 src/index.html 和然后在 src/app/app.component.ts 声明 declare var testvar;.

test.js

var testvar = "Hello from external js";

index.html

...
<link rel="icon" type="image/x-icon" href="assets/icon/favicon.ico">
<link rel="manifest" href="manifest.json">
<meta name="theme-color" content="#4e8ef7">

<!-- cordova.js required for cordova apps -->
<script src="cordova.js"></script>
<script src="assets/js/test.js"></script> //here, not in body
...

app.componet.ts

declare var testvar;

@Component({
templateUrl: 'app.html'
})
export class MyApp {
@ViewChild(Nav) nav: Nav;
constructor(private statusbar : StatusBar, splashScreen: SplashScreen) {
alert(testvar);
...

关于angular - 如何在 ionic 3 中包含 JS 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43833895/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com