Angular 检查是否在路线更改时调用了Ngondestory
我在“材质”选项卡中创建了一个子窗体组件:Angular 检查是否在路线更改时调用了Ngondestory,angular,Angular,我在“材质”选项卡中创建了一个子窗体组件: <md-tab *ngFor="let selectedEntity of selectedEntities; let i=index"> <template md-tab-label>{{selectedEntity.resource.name}} <i class="fa fa-times" (click)="onTabClose(i)"></i> </templ
<md-tab *ngFor="let selectedEntity of selectedEntities; let i=index">
<template md-tab-label>{{selectedEntity.resource.name}}
<i class="fa fa-times" (click)="onTabClose(i)"></i>
</template>
<child-form [entity]="selectedEntity"></child-form>
</md-tab>
但是,由于当前状态保存在服务中,因此当用户更改路由时,我不需要显示提示,仅当他们关闭选项卡时才会显示提示
我可以(如果可以,我可以如何)检查路由更改是否导致子组件被破坏吗?我在这里设法创建一个布尔属性,在
导航开始
事件上设置为真
,在导航结束
事件上设置为假
。这样,只有当路线导航结束时,我才能打开对话框。以下是我如何通过几个步骤解决这个问题:
1.我在我的prompt.service.ts
2.然后,在服务构造函数中,我订阅了导航事件,并相应地设置了inNavigation
:
constructor(private dialog: MdDialog, public router: Router) {
this.router.events.subscribe(event => {
if (event instanceof NavigationStart) {
this.inNavigation = true;
} else if (event instanceof NavigationEnd) {
this.inNavigation = false;
}
});
}
3.然后,我使用该布尔属性检查是否应打开提示对话框:
public open(entity: any): Observable<boolean> {
if (this.inNavigation == false) {
let dialogRef: MdDialogRef<PromptComponent>;
dialogRef = this.dialog.open(PromptComponent);
dialogRef.componentInstance.entity = entity;
return dialogRef.afterClosed();
}
}
一种方法是听路由器事件,如果你收到routerNavigationStart事件,知道路由正在进行,我基本上是这样做的,我会把整个事情作为一个答案发布。谢谢你给我指明了正确的方向!
public open(entity: any): Observable<boolean> {
if (this.inNavigation == false) {
let dialogRef: MdDialogRef<PromptComponent>;
dialogRef = this.dialog.open(PromptComponent);
dialogRef.componentInstance.entity = entity;
return dialogRef.afterClosed();
}
}
ngOnDestroy(): void {
this.promptService.open(this);
}