如何在Ionic 3中使用外部Javascript文件

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在Ionic 3中使用外部Javascript文件相关的知识,希望对你有一定的参考价值。

我试图从这个链接http://openexchangerates.github.io/money.js/转换不同格式的货币

我在我的assets / js /文件中复制了http://openexchangerates.github.io/money.js/money.js文件,名称为“converter.js”

我还在index.html文件中声明了这个文件:

<script src="assets/js/converter.js"></script>

现在我想将fx.convert(1, {from: "USD", to: "INR"});函数调用到我的home.ts文件中

我喜欢哪个

declare var fx;

alert(fx.convert(1, {from: "USD", to: "INR"}));

返回错误:

ERROR Error: fx error
at viewWrappedDebugError (VM263 vendor.js:10180)
at callWithDebugContext (VM263 vendor.js:15482)
at Object.debugCreateRootView [as createRootView] (VM263 vendor.js:14755)
at ComponentFactory_.create (VM263 vendor.js:11652)
at ComponentFactoryBoundToModule.create (VM263 vendor.js:4404)
at ViewContainerRef_.createComponent (VM263 vendor.js:11849)
at IonicApp.ngOnInit (VM263 vendor.js:54207)
at checkAndUpdateDirectiveInline (VM263 vendor.js:12785)
at checkAndUpdateNodeInline (VM263 vendor.js:14309)
at checkAndUpdateNode (VM263 vendor.js:14252)

如何完美地实现此功能。

先感谢您。

答案

在build / polyfills.js和build / main.js(它们在body标签中)之前,将导入js放在src / index.html标头标记中;

我创建了一个带有var测试的文件src / assets / test.js,在src / index.html中导入,然后在src / app / app.component.ts中声明了declare var test;。

test.js

var test = "Hello";

的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>

... app.componet.ts

declare var test;

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

以上是关于如何在Ionic 3中使用外部Javascript文件的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Ionic 3 中导入外部 JS 文件

ionic 3 的内页不适用于 ionic 3 中的脚本或外部自定义 jQuery 插件

ionic3引用外部插件--百度地图及echart报表的使用

如何在 Javascript 中读取 Ionic Webview 版本?

Ionic 3 - 如何打开富文本内容的网址(hrefs)

是否可以在 angularjs/ionic 移动应用程序中运行外部 js 脚本