![](/img/trans.png)
[英]How to Include External JavaScript Libraries In An Angular 4 TypeScript
[英]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
块)。
当使用外部加载到浏览器中的外部库时(例如通过 index.html),您只需要说明您的服务/组件它是通过“声明”定义的,然后就可以使用它。 例如,我最近在我的 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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.