将 js 脚本从 URL 导入到 Angular

Import js script to Angular from URL

我正在使用 angular 构建应用程序,但发现了一个我不知道如何解决的问题。 我需要导入一个 js 脚本,它必须从互联网上导入。 (因为这是他们的规则,所以他们可以做修补程序) 问题是,当我将脚本导入 index.html 时,我只能在 js 文件中使用它,而不能在 typescript 文件中使用。我如何在我的 ts 文件中使用库? 我无法通过 npm 安装它,也无法下载文件并将其添加到我的项目文件夹中。 图书馆是空调 API (https://developers.airconsole.com/#!/api)

感谢您的帮助

只有在你的组件中添加declare var AirConsole才能使用,傻瓜组件

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
}
 

更新 嗯,通常我们可以使用服务来管理 airConsole,这允许我们注入服务的所有组件都可以使用函数、变量、...

免责声明:我不知道“AirConsole”,所以我想像控制其他 .js 一样控制它,比如 Cordova)

因为我们需要 Angular 知道函数何时在 .js 中执行,我们的服务可以像

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

  }
}

所以,例如你可以订阅airConsoleService.message