我遇到一个奇怪的问题,在Angular 7中导航到特定路由时,我的一个路由参数订阅将停止更新。
这是我的路由器配置-
const routes: Routes = [
{
path: '',
component: OrganisationsRootComponent,
canActivate: [RequireAuthGuard],
children: [
{
path: 'new',
component: NewOrganisationComponent,
},
{
path: '',
component: ListComponent,
},
{
path: ':id',
component: ListComponent,
},
{
path: ':id/settings',
component: OrganisationSettingsComponent,
}
]
}
]
哪些是延迟加载的-
const routes: Routes = [
{ path: 'organisations', loadChildren: './organisations/organisations.module#OrganisationsModule' },
{ path: '', redirectTo: 'organisations', pathMatch: 'full' },
{ path: '**', redirectTo: 'organisations' },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule {
}
还有我的根组件-
export class OrganisationsRootComponent implements OnInit {
organisationId: string;
constructor(private route: ActivatedRoute) { }
ngOnInit(): void {
this.route.firstChild.params.subscribe(params => {
this.organisationId = params['id'];
console.log('org id', this.organisationId);
}
}
现在,当我导航到organisations/1
或organisations/2
时,该ID已记录到控制台。但是,如果我导航到organisations/2/settings
或organisations/new
,则订阅将停止工作,即使导航回organisations/1
或organisations/2
也不会记录任何内容。
有人可以解释为什么吗?
答案 0 :(得分:0)
在导航到“ organisations / 2 / settings”时,您能调试一下什么是您的firstChild信息和当前路线信息吗?
如果您订阅路由器事件,则可以监听所有路由器导航更改,而不是firstChild。
import { NavigationStart, Router } from '@angular/router';
private routeSub:any; // subscription to route observer
public ngOnInit() {
this.routeSub = this.router.events.subscribe((event) => {
if (event instanceof NavigationStart) {
// listen for changes
}
});
}
public ngOnDestroy() {
this.routeSub.unsubscribe();
}