Angular中vis.js network赋值选中节点到全局变量报错咨询
报错原因
普通function声明的事件回调会改变this的指向,你代码中回调内部的this不再指向当前Angular组件实例,而是指向vis.js的network事件上下文,TypeScript无法识别该上下文的类型,就会抛出'this' implicitly has type 'any' because it does not have a type annotation的错误,此时直接给this.selectedNode赋值自然也无法修改组件的全局变量。
解决方案
优先使用箭头函数写法,箭头函数不会生成独立的this上下文,会直接继承外层(即ngOnInit生命周期中组件实例)的this指向,写法简洁且TS可以正常做类型校验:
network.on('click', (properties) => { const nodeID = properties.nodes[0]; const edgeFrom = properties.edges; if (nodeID) { console.log("Selected node id:", nodeID); this.selectedNode = nodeID; } });
如果需要保留普通function的写法,可以选择以下两种方案:
- 提前在外层作用域缓存组件实例的引用,回调中通过缓存的引用赋值:
// 缓存当前组件实例的this const compRef = this; network.on('click', function (properties) { const nodeID = properties.nodes[0]; const edgeFrom = properties.edges; if (nodeID) { console.log("Selected node id:", nodeID); // 通过缓存的组件引用修改变量 compRef.selectedNode = nodeID; } });
- 通过
bind方法手动给回调绑定组件实例的this:
network.on('click', function (properties) { const nodeID = properties.nodes[0]; const edgeFrom = properties.edges; if (nodeID) { console.log("Selected node id:", nodeID); this.selectedNode = nodeID; } }.bind(this)); // 手动绑定外层组件的this到回调函数
日常Angular开发中优先选箭头函数方案,代码可读性更高,也不会出现this指向混乱的问题。
内容的提问来源于stack exchange,提问作者sphcstrs
相关产品推荐
相关产品推荐

