如何在 Angular 2 中包含外部 JavaScript 库
How to include external JavaScript libraries in Angular 2?
我正在尝试在我的 Angular 2 应用程序中包含一个外部 JS 库,并尝试将该 JS 文件中的所有方法作为 Angular 2 应用程序中的服务。
例如:假设我的JS文件包含。
var hello = {
helloworld : function(){
console.log('helloworld');
},
gmorning : function(){
console.log('good morning');
}
}
所以我正在尝试使用这个JS文件并重用这个对象中的所有方法并将其添加到服务中,以便我的服务具有公共方法,而公共方法又调用此JS方法。我正在尝试重用代码,而无需在基于打字稿的 Angular 2 应用程序中重新实现所有方法。我依赖于无法修改的外部库。请帮忙,提前谢谢你。
使用 ES6,您可以导出变量:
export var hello = {
(...)
};
并像这样将其导入到另一个模块中:
import {hello} from './hello-module';
假设第一个模块位于hello-module.js
文件中,并且与第二个模块位于同一文件夹中。没有必要将它们放在同一个文件夹中(您可以执行以下操作:import {hello} from '../folder/hello-module';
)。重要的是 SystemJS 正确处理了该文件夹(例如,使用 packages
块中的配置)。
当使用外部加载到浏览器中的外部库(例如通过索引.html)时,你只需要说出你的服务/组件是通过"declare"定义的,然后使用它。例如,我最近在我的 angular2 组件中使用了 socket.io:
import { Component, Input, Observable, AfterContentInit } from angular2/angular2';
import { Http } from 'angular2/http';
//needed to use socket.io! io is globally known by the browser!
declare var io:any;
@Component({
selector: 'my-weather-cmp',
template: `...`
})
export class WeatherComp implements AfterContentInit{
//the socket.io connection
public weather:any;
//the temperature stream as Observable
public temperature:Observable<number>;
//@Input() isn't set yet
constructor(public http: Http) {
const BASE_URL = 'ws://'+location.hostname+':'+location.port;
this.weather = io(BASE_URL+'/weather');
//log any messages from the message event of socket.io
this.weather.on('message', (data:any) =>{
console.log(data);
});
}
//@Input() is set now!
ngAfterContentInit():void {
//add Observable
this.temperature = Observable.fromEvent(this.weather, this.city);
}
}
相关文章:
- 在哪里可以学习ECMAScript标准中尚未包含的JavaScript功能
- 从我自己的脚本中包含的Javascript文件中调用一个函数
- 在JavaFX的String中包含本地javascript源
- 在脚本标记中包含一个javascript文件
- 如何在 Angular 2 中包含外部 JavaScript 库
- 如何在没有冲突的情况下将 JQuery 包含在 JavaScript 文件中
- 如果 URL 包含使用 JavaScript 重定向的特定端口
- YepNope/Modernizr 回调,包含全局 JavaScript 变量和 Internet Explorer
- 如何查找不同页面上是否确实需要包含的JavaScript文件
- 我们如何捕捉主文件中包含的javascript文件引发的错误
- 包含的javascript源代码通过PHP,onmousemove事件,函数未定义
- 将jQuery包含到javascript中,并在imacros中使用它
- 设置一个复选框,其中包含使用javaScript检查的特定名称和id
- 删除HTML脚本标记会对它所包含的JavaScript产生任何影响吗
- 如何在PHP中包含动态Javascript页面的静态HTML结果
- 如何在 BIRT 脚本数据源中包含外部 Javascript
- 如何将OpenCV包含在JavaScript项目中
- 如何在 reactjs 中包含外部 JavaScript 库
- 确认框包含使用 JavaScript 的数据和图像
- 如何在Chrome扩展名的内容JS文件中包含其他JavaScript文件