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

How to include external JavaScript libraries in Angular 2?

本文关键字:包含外 JavaScript Angular      更新时间:2023-09-26

我正在尝试在我的 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);
    }
}