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

Angular 2 - communication of typescript functions with external js libraries

使用Javascript Infovis Toolkit 作为绘制图形和树的外部库。我需要操作节点的 onClick 方法,以便向服务器异步发送 HTTP GET 请求,并将来自服务器的数据分配给 Angular 服务 class 的属性和变量。通过使用 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服务树的绘制完成,可以查询所有的节点?[​​=14=]

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

在 Angular 中,您可以通过添加到实际添加到 DOM:

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

其中 custom-event 是调度事件的类型,updateNodes(event) 是组件中的方法 class。

要在JavaScript中手动触发:

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

另一种方法

将使组件(或指令、服务)的方法在 Angular 之外可用,如 中所述。