Angular 2 - typescript函数与外部 js 库的通信

IT技术 javascript typescript angular webpack angular2-services
2021-02-26 01:39:14

使用Javascript Infovis Toolkit作为绘制图形和树的外部库。我需要操作节点的 onClick 方法,以便向服务器异步发送 HTTP GET 请求,并将来自服务器的数据分配给 Angular 服务类的属性和变量。通过使用 webpack 将所有编译好的typescript打包到单个 js 文件中,输出文件令人困惑且不可读。因此,从外部 js 库调用已编译的 js 文件中的函数显然不是最佳解决方案。

我在我的 Angular 服务中尝试了以下解决方案,以便我可以毫无困难地访问该服务的属性:

document.addEventListener('DOMContentLoaded', function () {
  
  var nodes = document.querySelectorAll(".nodes"); // nodes = []
  
  for (var i = 0; i < nodes.length; i++) { // nodes.length = 0
    
    nodes[i].addEventListener("click", function () {
      
      // asynchronously sending GET request to the server
      // and assing receiving data to the properties of this Angular service
      
    });
  }

});

但是,此解决方案不起作用,因为在 Javascript Infovis Toolkit 中,节点是在完成 DOM 渲染之后以及在window.onload事件之后绘制的该库有一些生命周期方法,例如在绘制树完成后调用的 onAfterCompute() 。如何触发全局事件以通知 Angular 服务树的绘制已完成并且它可以查询所有节点?

1个回答

只需使用dispatchEvent触发自定义事件

在 Angular 中,您可以通过添加到实际添加到 DOM 的任何组件来监听:

  • 在任何模板中:
<div (window:custom-event)="updateNodes($event)">
  • 或在组件类中:
@HostListener('window:custom-event', ['$event']) 
updateNodes(event) {
  ...
}
  • 或在@Component()@Directive()注释中:
@Component({
  selector: '...',
  host: {'(window:custom-event)':'updateNodes($event)'}
})

wherecustom-event是分派事件的类型,updateNodes(event)是组件类中的一个方法。

在 JavaScript 中手动触发它:

window.dispatchEvent(new Event('custom-event'));

另一种方法

将是使组件(或指令、服务)的方法在 Angular 之外可用,就像Angular2 中解释的那样 - 如何从应用程序外部调用组件函数