Angular 为组件的每个实例触发事件处理程序
Angular Event handler firing for every instance of component
我有一个页面 (hostview),我在其中动态创建了包含信息的组件,包括用户在 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() {}
}
树组件:
服务:通知服务;
constructor(public dataCenter: DataCenterService, public treeService: TreeDragDropService, service:NotificationService) {
this.service = service;
}
ngOnDestroy() {
this.service.onDestroyEvent.emit(this.ref); /*ComponentRef passed back to hostview*/
}
所以这在技术上是可行的,但它会为树组件的每个实例调用一次,而不是只调用一次。我该如何解决这个问题才能正常工作?
我去掉了NotificationService,把onDestroyEvent放到了树组件中,并进行了相应的重构。这解决了重复事件问题。
我有一个页面 (hostview),我在其中动态创建了包含信息的组件,包括用户在 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() {}
}
树组件:
服务:通知服务;
constructor(public dataCenter: DataCenterService, public treeService: TreeDragDropService, service:NotificationService) {
this.service = service;
}
ngOnDestroy() {
this.service.onDestroyEvent.emit(this.ref); /*ComponentRef passed back to hostview*/
}
所以这在技术上是可行的,但它会为树组件的每个实例调用一次,而不是只调用一次。我该如何解决这个问题才能正常工作?
我去掉了NotificationService,把onDestroyEvent放到了树组件中,并进行了相应的重构。这解决了重复事件问题。