首页 > 解决方案 > 在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 = {} 中)

标签: angulartypescriptinteractjs

解决方案


你的问题的根源是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) }
        })
}

推荐阅读