【问题标题】:Angular Event handler firing for every instance of component为组件的每个实例触发 Angular 事件处理程序
【发布时间】:2019-10-24 22:54:58
【问题描述】:

我有一个页面(主机视图),我在其中动态创建包含信息的组件,包括用户在 UI 中创建的 p-tree。我使用主机视图中的按钮添加它们,并使用树组件上的按钮删除它们,该按钮通过通知服务将事件传递回主机视图,如下所示:

在主机视图中创建:

constructor(@Inject(Loader) service, @Inject(ViewContainerRef) viewContainerRef, public dataCenter: DataCenterService,private router: Router) {
    this.service = service;
    this.trees = this.dataCenter.getTreeState();
    this.service.setRootViewContainerRef(viewContainerRef)
    this.newTree();
}



newTree() {
    var newTree = this.service.addDynamicComponent();
    newTree.instance.ref = newTree;

    newTree.instance.service.onDestroyEvent.subscribe(
      treeRef => {
        for(var i=0;i<this.trees.length; i++){
          if(this.trees[i].instance.ref == treeRef){
            this.trees.splice(i,1);
          }
        }
       }
      );
    this.trees.push(newTree);
}

通知服务:

export class NotificationService {
    onDestroyEvent: EventEmitter<ComponentRef<ConnectionTreeComponent>> = new EventEmitter();
    constructor() {}
}

树组件:

服务:通知服务;

constructor(public dataCenter: DataCenterService, public treeService: TreeDragDropService, service:NotificationService) {
   this.service = service; 
}

ngOnDestroy() {
   this.service.onDestroyEvent.emit(this.ref); /*ComponentRef passed back to hostview*/
}

所以这在技术上确实有效,但它会为树组件的每个实例调用一次,而不仅仅是一次。我该如何解决这个问题才能正常工作?

【问题讨论】:

    标签: angular events event-handling components


    【解决方案1】:

    我删除了 NotificationService 并将 onDestroyEvent 放入树组件中,并进行了相应的重构。这解决了重复事件问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-15
      • 1970-01-01
      • 1970-01-01
      • 2012-04-15
      • 2011-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多