【问题标题】:Using external library variable in app.component.ts file in angular4在 angular4 的 app.component.ts 文件中使用外部库变量
【发布时间】:2018-11-22 08:55:11
【问题描述】:

我想使用在 app.component.ts 文件的外部 js 库中声明的全局变量 cwic。 js 库作为 cwic-debug.js 保存在 assets 文件夹中。现在要初始化库并使用 cwic 变量,必须将声明 SystemController 方法调用为-

cwic.SystemController.initialize() 

index.html

<script type="text/javascript" src="./assets/cwic-debug.js"></script>

我已经尝试通过以下方式初始化 cwic 库-

app.component.ts-

 export class AppComponent implements AfterViewInit{
  ngAfterViewInit(){
    cwic.SystemController.initialize();
    console.log(cwic);
  }
  title = 'Angular Project';
}

但由于 cwic 变量无法识别,因此会引发错误并在 cwic 单词下划线为红色。

js 库,即 cwic-debug.js 看起来像这样-

var cwic =
/******/ (function(modules) { // webpackBootstrap
/******/    // The module cache
/******/    var installedModules = {};
/******/
/******/    // The require function
/******/    function __webpack_require__(moduleId) {
/******/

如何在 app.component.ts 文件中使用这个 cwic 变量?

【问题讨论】:

    标签: javascript angular angular2-template angular6


    【解决方案1】:

    您可以声明变量并将其键入为any

    declare var cwic: any;
    

    TypeScript 将停止抱怨变量的类型并假设它存在,但您将不再从 IDE 获得类型帮助。

    【讨论】:

    • 非常感谢!它有帮助!但是有没有其他方法可以将 cwic 变量导入到 app.component.ts 文件中?
    • 我不知道 cwic 是什么,但如果库只是注入到 JS 域中,可能不会。您可以查找该库是否提供 typescript 类型文件 (*.d.ts),其中仅包含 typescript 的类型注释,然后您可以导入这些文件。
    猜你喜欢
    • 2017-09-29
    • 1970-01-01
    • 2020-07-11
    • 1970-01-01
    • 1970-01-01
    • 2022-11-11
    • 2023-03-21
    • 2019-02-28
    • 2016-10-02
    相关资源
    最近更新 更多