首页 > 解决方案 > 角度活动路由参数订阅未更新

问题描述

我遇到了一个奇怪的问题,当导航到 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/1organisations/2将 id 记录到控制台时。但是,如果我导航到organisations/2/settingsorganisations/new订阅停止工作,即使导航回organisations/1organisations/2没有记录任何内容。

有人能解释这是为什么吗?

标签: angular

解决方案


您可以在导航到“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();
  }

推荐阅读