我有一个页面(主机视图),在其中我动态创建包含信息的组件,这些组件包括用户在UI中创建的p树。我从主机视图中添加了一个按钮,并在树组件上单击了按钮,将它们删除,该组件通过notificationService将事件传递回主机视图,如下所示:
在主机视图中创建:
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() {}
}
树组件:
service:NotificationService;
constructor(public dataCenter: DataCenterService, public treeService: TreeDragDropService, service:NotificationService) {
this.service = service;
}
ngOnDestroy() {
this.service.onDestroyEvent.emit(this.ref); /*ComponentRef passed back to hostview*/
}
因此这在技术上确实有效,但是对于树组件的每个实例都调用一次,而不是一次。我该如何解决才能正常工作?
答案 0 :(得分:0)
我删除了NotificationService并将onDestroyEvent放入树组件中,并进行了相应的重构。这样就解决了重复事件的问题。