angular - 角度活动路由参数订阅未更新
问题描述
我遇到了一个奇怪的问题,当导航到 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
没有记录任何内容。
有人能解释这是为什么吗?
解决方案
您可以在导航到“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();
}
推荐阅读
- python - 带有 .nii.gz 文件的医学成像 (PyRadiomics)
- python - 在python中使用可变数量的所需填充参数格式化字符串
- java - 如何通过反射获取函数对象的类型参数?
- python - 为什么 bash echo 为退出 1 的 Python 函数打印 0
- python - Pyqtgraph 类:如何从数据缓冲区自动更新图形值?
- html - 对齐中心下拉菜单 Bootstrap 4
- javascript - 如何从对象内部的真假显示元素?Javascript ReactJs
- c# - .NET Core 中的环境标记帮助程序
- javascript - Node.JS 中的 `import` 支持是个谎言
- javascript - Koa, Node.js, Server - 如何从 Server 对象中获取 Koa 的路由器级中间件功能?