我搜索了几个小时,但没有找到任何类似的帖子。
问题描述:
我单击routeA组件中的一个按钮,它将导航到routeB并打开一个dialogB,然后在我关闭此对话框B之后,它将导航回到routeA。在routeA组件的构造函数中,当初始化此组件时(在constructor()内部),我有一个dialogA打开。并且错误发生在控制台中,表示在routeA组件中存在一个错误,该错误指向构造函数中dialogA的EventEmitter。
无法读取未定义的属性“ subscribe”
我可以使用
解决这个问题path = window.location.pathname;
然后仅检查路径是否等于目标组件的路径
if (path != '/merchant/(page:home)' && path != '/merchant'){
但是情况是,我确实有几个组件具有相同的逻辑以从其构造函数中打开对话框,这使此批准的可维护性较差。而且,只有那些包含在构造函数中打开对话框的代码的组件才会发生这种情况。
我想知道有什么办法可以解决我的问题,还是应该重新设计我的结构?
用于说明问题的示例代码
带有dialogA的routeA组件:
constructor() {
let ref = this.dialog.open(DashboardIntroModalComponent, {
width: "800px",
panelClass: "noCard"
});
if (ref.componentInstance.showOnDashLogin == true) {
ref.close();
}
else {
const sub = ref.componentInstance.closeModal.subscribe(data => {
ref.close();
});
// const tour = ref.componentInstance.startTour.subscribe(data => {
// ref.close();
// this.startTour();
// });
}
}
打开对话框B:
let ref = AppComponent.dialog.open(LookupComponent, {
data: {
autoFocus: true,
isModal: true
},
width: "650px",
});
ref.componentInstance.getResult.subscribe(res => {
if (res) {
ref.close();
this.router.navigate([
"/merchant",
{
outlets: {
page: ['customer-profile', res['ID']]
}
}
])
}
})
let path = window.location.pathname;
ref.componentInstance.close.subscribe(res => {
if (res == true) {
ref.close();
this.location.back()
}
})
答案 0 :(得分:0)
我相信这个问题是因为“ res”变量在初始化之前已执行。尝试将构造函数内部的代码添加到ngAfterViewInit()
方法中。
RouteA //在类中实现AfterViewInit
Constructor () { }
ngAfterViewInit () {
let ref = this.dialog.open(DashboardIntroModalComponent, {
width: "800px",
panelClass: "noCard"
});
if (ref.componentInstance.showOnDashLogin == true) {
ref.close();
}
else {
const sub = ref.componentInstance.closeModal.subscribe(data => {
ref.close();
});
}
}
答案 1 :(得分:0)
我通过在设置路由时在data属性中添加一个额外的字段来解决此问题。
类似的东西
const routes: Routes = [
{
path: 'componet path',
component: ComponentPath,
data: { openDialog: 'componet path' },
outlet: 'page'
},
]
在我的routeA组件中
ngInit() {
this.router.events
.filter(event => event instanceof NavigationEnd)
.map(() => this.activatedRoute)
.map(route => {
while (route.firstChild) route = route.firstChild;
return route;
})
.mergeMap(route => route.data)
.subscribe(event => {
if (event['openDialog']) {
this.routerPath = event['openDialog'];
this.hasDialogInConstrcutor = true;
}
});
}
按钮打开对话框A
ref.componentInstance.close.subscribe(res => {
if (res == true) {
ref.close();
if (this.hasDialogInConstrcutor == true) {
this.router.navigate([
'/merchant', {
outlets: {page: [this.routerPath]}
}
]);
}
else {
this.location.back();
}
}
})