第二次使用 ng2-dragula 进入页面时出错

Getting error second time getting to page with ng2-dragula

我试图阻止用户移动 dragulaService 的第一个元素,代码第一次运行时没有任何错误,但是当我离开此页面然后再次打开它时,出现错误。

导致错误的代码:

constructor(public service:SmartTablesService, private dragulaService:DragulaService) {
    dragulaService.setOptions('nested-bag', {
      revertOnSpill: true,
      moves: function (el:any, container:any, handle:any):any {
        if (handle.className === 'sorting-table-title') {
          return false;
        } else {
          return true;
        }

      }
    });

错误是:

error_handler.js:48 EXCEPTION: Uncaught (in promise): Error: Error in ./SortTableComponent class SortTableComponent_Host - inline template:0:0 caused by: Bag named: "nested-bag" already exists. Error: Bag named: "nested-bag" already exists. at DragulaService.add (http://platform.local:8080/3.chunk.js:1070:19) at DragulaService.setOptions (http://platform.local:8080/3.chunk.js:1099:24) at new SortTableComponent (http://platform.local:8080/3.chunk.js:1311:24)

您需要在组件的 onDestroy 生命周期中手动销毁 nested-bag,因为它不会自动完成:

ngOnDestroy() {
    this.dragulaService.destroy('nested-bag');
}

最好为每个使用拖放的 Angular 组件提供唯一的 DragulaService,而不是共享公共服务:

@Component({
   ...,
   providers: [DragulaService],
   ...
})
export class MyComponent {
...
}

Source