【问题标题】:How to import or use external JS files and functions in my angular web application如何在我的 Angular Web 应用程序中导入或使用外部 JS 文件和函数
【发布时间】:2019-03-28 15:03:38
【问题描述】:

我想将外部代码(html、js 和 css 文件)集成到我的 Angular Web 应用程序中。

在这个外部代码中,HTML文件是这样的:

index.html

<html>
<header>
</header>
<body>
</body>

 <script src="app/components/landing-page/js/bootstrap.min.js"></script>
  <script src="app/components/landing-page/js/owl.carousel.min.js"></script>
  <script src="app/components/landing-page/js/cbpAnimatedHeader.js"></script>
  <script src="app/components/landing-page/js/theme-scripts.js"></script>
  <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
  <script src="app/components/landing-page/js/ie10-viewport-bug-workaround.js"></script>
  <script type="text/javascript" src="app/components/landing-page/js/imageComparisonSlider.js"></script>
  <script>
    /*Execute a function that will execute an image compare function for each element with the img-comp-overlay class:*/
    initComparisons();
  </script>
<html>

如您所见,有几个 javascript 文件,并且将调用函数 initComparisons()。

如果我只双击 index.html,一切正常。但是我将此html代码复制到一个component.html中,但不起作用。我看不到任何动画。

我搜索了一些解决方案, 我已经像这样更改了我的 angular.json 文件:

 "scripts": [
              "src/app/components/landing-page/js/imageComparisonSlider.js",
              "src/app/components/landing-page/js/owl.carousel.min.js",
              "src/app/components/landing-page/js/cbpAnimatedHeader.js",
              "src/app/components/landing-page/js/theme-scripts.js"
            ]

并在我的 Angular Web 应用程序中导入 index.html 中的所有 js 文件

 <script src="app/components/landing-page/js/imageComparisonSlider.js"></script>
  <script src="app/components/landing-page/js/owl.carousel.min.js"></script>
  <script src="app/components/landing-page/js/theme-scripts.js"></script>
  <script src="app/components/landing-page/js/cbpAnimatedHeader.js"></script>

在component.ts中,我也是这样做的:

import initComparisons from './js/imageComparisonSlider.js';
ngOnInit() {
    this.isLoggedIn = this.authService.isLoggedIn;
    initComparisons();
  }

我在 stackblitz 中添加了一些代码; https://stackblitz.com/edit/angular-qowfwy?file=angular.json

但它不起作用。

谁能帮助我并给我一些建议。

最好的问候,

狮子座

【问题讨论】:

标签: javascript angular animation external-js


【解决方案1】:

如果你想在你的 Angular 项目中使用外部 js,你必须在 "scripts": [] 区域中导入你的 angular.json,这将允许你带来 js 并在没有问题之后进行构建。

【讨论】:

  • 运行ng build后没有问题
【解决方案2】:

将外部脚本放入 angular.json(路径正确且一切正常)后,您应该在组件中

declare const initComparisons;
// ...
ngOnInit() {
  initComparisons();
}

【讨论】:

  • 路径正确,我运行 ng build 并成功。
  • 为什么要使用declare const?
  • 因为没有它,TypeScript 将反对使用未声明的值initComparisons,我预计会出现构建错误。
  • 但是我已经导入了这个外部js文件的功能
  • 你的意思是;从'./js/imageComparisonSlider.js'导入{initComparisons};声明 const initComparisons;
猜你喜欢
  • 1970-01-01
  • 2023-03-30
  • 2020-02-15
  • 2017-10-22
  • 1970-01-01
  • 1970-01-01
  • 2021-12-31
  • 1970-01-01
  • 2018-11-23
相关资源
最近更新 更多