0

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

谢谢你的帮助

4

1 回答 1

1

它只是添加到你的组件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,这让我们所有注入服务的组件都可以使用函数,变量,...

Disclamer:我不了解“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

于 2021-07-14T07:18:23.357 回答