我有两条参数化路线
{ path: 'mails', component: MailsComponent, canActivate: [AuthGuard] },
{ path: 'mails/:label', component: MailsComponent, canActivate: [AuthGuard] },
{ path: 'mails/folder/:folder', component: MailsComponent, canActivate: [AuthGuard] }
在组件中,我想根据条件获取路由参数。
ngOnInit(): void{
if (this.googleAuth.stateFlag) {
// labels
this.route.paramMap.subscribe(route => {
this.label$ = route.get('label');
this.googleAuth.selectedEmailLabel(this.label$);
});
}
else {
// folder
this.route.paramMap.subscribe(route => {
this.folder$ = route.get('folder');
console.log('folder handle:', this.folder$);
this.googleAuth.selectedEmailFolder(this.folder$);
});
}
}
尽管有条件,但每次执行else块。
此问题很可能是因为ngOnInit
在组件的生命周期中仅被调用一次,并且该组件可在更改路线时多次使用。尝试一次订阅paramMap,并在以下方法中处理逻辑:
ngOnInit(): void{
this.route.paramMap.subscribe(route => {
if (this.googleAuth.stateFlag) {
this.label$ = route.get('label');
...
} else {
this.folder$ = route.get('folder');
...
}
});
}