angular是目前国内并不火的一个框架,由于公司高层选型,笔者不得不使用之。用惯了之后觉得也挺好,也能做出很棒的效果。但笔者经常会遇到一个问题,由于angular全面采用typescript写法和独特的项目组织方式,有时需要引入某些第三方原生js库,这些库并没有angular版本,用法也是像传统JavaScript一样,和angular风格迥异。
刚开始时,笔者经常会选用一些有angular版本的第三方库,例如https://swimlane.github.io/ngx-graph/这样的一些传统js库的angular版本。然而久而久之,由于angular版本的第三方库太少,根本无法满足需求,并且这些库用的人少,bug也多,不成气候。所以不得不重新转向使用原生js库,所以有个问题就不得不面对了,如何在angular项目中引入第三方原生js库?
本文以蚂蚁金服的可视化方案AntV-G6为例,描述如何在angular项目中引入原生的G6 JavaScript库。如果我们想引入这个工作流图,https://antv.alipay.com/zh-cn/g6/2.x/demo/flow/work-flow.html,该怎么做呢?
- 假设我们新建了一个angular项目,并且就打算在app.component中画这幅图。为了专注如何引入js库这个主题,避免不同版本的坑,本文不使用npm安装G6,而是直接将这两个文件复制下来,保存在src/assets/js目录下。分别命名为g6.js和plugins.js
- 打开angular.json,在scripts下加入
"src/assets/js/g6.js","src/assets/js/plugins.js"
- 在src/app/app.component.html中加入
<div id="mountNode"></div>
-
在src/app/app.component.ts中新写一个函数,比如render(),并将https://antv.alipay.com/zh-cn/g6/2.x/demo/flow/work-flow.html中<script>标签下的代码拷贝到render函数中。这时我们发现编译器并不认识G6这个变量,于是我们在头部的import下面,加上
declare var G6:any;
这句的意思就是告诉angular,G6这个变量你后面能找到的,先不用检查了。
-
在src/app/app.component.ts中的ngOnInit函数中,引用render()函数。使用ng s 命令重新运行angular应用,就能发现图已经画出来了。
-
由于某种原因,有时直接在ngOnInit函数中直接调用render函数会报container: 'mountNode'找不到,这种情况可以让AppComponent实现AfterViewInit接口,并在ngAfterViewInit使用
setTimeout(this.render(),100);
这种延迟加载的形式,确保html渲染完毕后,再运行render函数。
-
附上源码:src/app/app.component.html
<div id="mountNode"></div>
src/app/app.component.ts
import {AfterViewInit, Component, OnInit} from '@angular/core'; declare var G6:any; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent implements OnInit,AfterViewInit { constructor() { } ngOnInit(): void { // this.render(); } ngAfterViewInit(): void { setTimeout(this.render(),100); } render(){ G6.registerNode('rect', { getPath: function getPath(item) { var width = 100; // 一半宽 var height = 40; // 一半高 return G6.Util.getRectPath(-width / 2, -height / 2, width, height, 10); } }); var data = { nodes: [{ id: '收集日志' }, { id: '入 es 集群' }, { id: '入 hdfs' }, { id: 'hive 计算' }, { id: 'report' }], edges: [{ source: '收集日志', target: '入 es 集群' }, { source: '收集日志', target: '入 hdfs' }, { source: '入 hdfs', target: 'hive 计算' }, { source: '入 es 集群', target: 'hive 计算' }, { source: 'hive 计算', target: 'report' }] }; var graph = new G6.Graph({ container: 'mountNode', fitView: 'cc', height: window.innerHeight, // 画布高 plugins: [new G6.Plugins['layout.dagre']()], defaultIntersectBox: 'rect' // 使用矩形包围盒 }); graph.node({ shape: 'rect', label: function label(model) { return model.id; }, style: { stroke: '#00C0A5', fill: '#92949F', fillOpacity: 0.45, lineWidth: 2 } }); graph.edge({ style: { endArrow: true } }); graph.read(data); } }
-
本文到此结束,祝大家能顺利引入第三方js库,少踩坑