angular - 在interactJS的结束回调函数中使用可注入服务
问题描述
我正在使用带角度的interactJS,以使用户可以使用“可拖动”类执行元素的拖放操作。一切正常,直到我需要在结束拖动的回调函数中使用组件的注入服务。这是我尝试过的:
ngOnInit() {
interact('.draggable')
.draggable({
inertia: true,
modifiers: [
interact.modifiers.restrictRect({
restriction: 'parent',
endOnly: true
})
],
autoScroll: true,
listeners: { move: this.dragMoveListener, end: this.stackForUndo }
})
}
stackForUndo() {
// get current state of svg
let current_state = document.getElementById("Logo").outerHTML;
// clear redo stack
this.menuService.redo = {}
// get the previous saved actions
let actions = { elements: [] };
// if no action has been cached, initialise the localStorage undo element
if (actions == undefined) {
actions = { elements: [] };
// save stringified empty action to localStorage
this.menuService.undo = actions;
}
// add the current state of the svg
if(actions.elements.length >= 5){
actions.elements.shift();
}
actions.elements.push(current_state);
this.menuService.undo = actions;
}
拖动后,我无法放下元素并在浏览器控制台中出现以下错误
无法读取未定义的属性 menuService(在 this.menuService.redo = {} 中)
解决方案
你的问题的根源是stackForUndo
丢失的上下文,为了解决这个问题,我只将它绑定到组件,如下所示:
ngOnInit() {
interact('.draggable')
.draggable({
inertia: true,
modifiers: [
interact.modifiers.restrictRect({
restriction: 'parent',
endOnly: true
})
],
autoScroll: true,
listeners: { move: this.dragMoveListener, end: this.stackForUndo.bind(this) }
})
}
推荐阅读
- snakemake - Snakemake 运行子工作流程,但不运行我的工作流程的其余部分(直接转到全部规则)
- c++ - 如何从随机值范围内删除某个元素?
- visual-studio-code - 是否可以在不删除未使用的导入的情况下启用 source.organizeImports?
- android - 如何在颤振中创建三次单击按钮
- excel - 将文件夹中特定的excel文件复制到主工作表中
- r - 按字母顺序重新排列垂直轴并更改堆叠百分比条形图(ggplot2)的二进制变量的位置
- ruby - 如何在 Ruby 2.7.0 上安装 Nokogiri
- python - 我可以使用 pyspark 将复杂的 json 对象转换为 Azure Databricks 中数据框中的多行吗?
- mysql - 如何在 MySQL 中查找列是否为 auto_increment
- javascript - 错误:找不到模块 './components/fb-comment-embed/fb-comment-embed' - Angular Universal 与 ngx-facebook 模块