Vijith
Vijith

Reputation: 163

How to include external JavaScript libraries in Angular 2?

I am trying to include an external JS library in my Angular 2 app and trying to make all the methods in that JS file as a service in Angular 2 app.

For eg: lets say my JS file contains.

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

So I am trying to use this JS file and reuse all the methods in this object and add it to a service, so that my service has public methods, which in turn calls this JS methods. I am trying to reuse the code, without reimplementing all the methods in my typescript based Angular 2 app. I am dependent on an external library, which I cant modify. Please help, thank you in advance.

Upvotes: 2

Views: 5173

Answers (2)

DeusProx
DeusProx

Reputation: 197

When using external libs which are loaded into the browser externally (e.g. by the index.html) you just need to say your services/component that it is defined via "declare" and then just use it. For example I recently used socket.io in my angular2 component:

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);
    }
}

Upvotes: 1

Thierry Templier
Thierry Templier

Reputation: 202296

With ES6, you could export your variable:

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

and import it like this into another module:

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

assuming that the first module is located into the hello-module.js file and in the same folder than the second one. It's not necessary to have them in the same folder (you can do something like that: import {hello} from '../folder/hello-module';). What is important is that the folder is correctly handled by SystemJS (for example with the configuration in the packages block).

Upvotes: 1

Related Questions