javascript - 如何在 Angular 2 中包含外部 JavaScript 库?

标签 javascript angular typescript

我试图在我的 Angular 2 应用程序中包含一个外部 JS 库,并尝试将该 JS 文件中的所有方法作为 Angular 2 应用程序中的服务。

例如:假设我的 JS 文件包含。

var hello = {
   helloworld : function(){
       console.log('helloworld');
   },
   gmorning : function(){
      console.log('good morning'); 
   }
}

所以我尝试使用这个JS文件并重用这个对象中的所有方法并将其添加到服务中,以便我的服务具有公共(public)方法,从而调用这个JS方法。我正在尝试重用代码,而不重新实现基于 typescript 的 Angular 2 应用程序中的所有方法。我依赖于一个外部库,我无法修改它。 请帮忙,先谢谢您。

最佳答案

使用 ES6,您可以导出变量:

export var hello = {
  (...)
};

并将其像这样导入到另一个模块中:

import {hello} from './hello-module';

假设第一个模块位于 hello-module.js 文件中,并且与第二个模块位于同一文件夹中。不必将它们放在同一个文件夹中(您可以执行类似的操作:import {hello} from '../folder/hello-module';)。重要的是 SystemJS 正确处理该文件夹(例如使用 packages block 中的配置)。

关于javascript - 如何在 Angular 2 中包含外部 JavaScript 库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36795060/

相关文章:

javascript - Android浏览器运行javascript window.close()?

javascript - 文本区域的 dom 名称

angular - 数据绑定(bind)不更新 w/嵌套 ngFor 循环

javascript - 创建秒表时出错

javascript - 如何在 React Native 项目中使用 Node.JS 中的 Crypto 内置模块?

javascript - 图像调整大小 NaN 错误

javascript - "html?v=<%= VERSION %>"是什么意思?

angular - 跨多个项目共享一个 Angular 库

Angular 2 - (SystemJS) 模块 'ViewerComponent' 导入的意外指令 'GalleryModule'

angular - 在 App.modules.ts 中注册的模块在其他模块中不可用