Search code examples
javascriptangulartypescriptimportairconsole

Import js script to Angular from URL


i am building an app with angular but found a problem I don't know how to solve. I need to import a js script and it has to be imported from the internet. (because these are their rules, so that they can do hotfixes) The problem is, when I import the script into my index.html I can only use it in js files not in the typescript files. How can i use the libary in my ts files? I can't install it via npm and i also can't download the file and add it to my project folder. The libary is the airconsole API (https://developers.airconsole.com/#!/api)

Thanks for your help


Solution

  • it's only add in your component declare var AirConsole to use it, a fool Component

    import { Component, VERSION } from '@angular/core';
    
    declare var AirConsole //<--this is the "magic"
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent  {
      name = 'Angular ' + VERSION.major;
      airConsole=new AirConsole() //<--now you can use airConsole in your component
    }
     
    

    Update Well, generally we can use a service to mannage the airConsole, this allow us that all components that inject the service can use the functions,variables,...

    Disclamer: I don't know about "AirConsole", so I imagine control it like we can control others .js like Cordova)

    As we need that Angular know when a function is executed in .js, our service can be like

    import { Injectable,NgZone } from '@angular/core';
    
    declare var AirConsole;
    
    @Injectable({
      providedIn: 'root',
    })
    export class AirConsoleService implements OnInit {
    
      airConsole=new AirConsole()
    
      message:Subject=new Subject<any>();
    
      constructor(private ngZone: NgZone) { }
    
      ngOnInit(){
         this.airconsole.onMessage = (from, data)=>{
          this.ngZone.run(() => {
            this.message.next({from:from,data:data})
          });
    
         })
      }
    
      message(device:any,message:any){
          this.ngZone.run(() => {
            this.airConsole.message(device,message);
          });
    
      }
    }
    

    So, e.g. you can subscribe to airConsoleService.message