Angular 9 条路线儿童未在导航上工作

Angular 9 route children not working on navigation

我有一个父路径的子路径,但是当我调用它时,它将 url 更改为正确的路径,但加载 ProductDetailsComponent 而不是 ChangeEmailComponent

应用-routing.ts

 const routes: Routes = [
  { path: '', redirectTo: '/home', pathMatch: 'full'},
  { path: 'home', component: HomeComponent },
  { path:':productName/:productId', component: ProductDetailsComponent },
  { path:'perfil', component: ProfileComponent, children: [
    { path: 'email', component: ChangeEmailComponent },
  ]},
  { path: '404', component: NotFoundComponent },
  { path: '**', redirectTo: '/404'}
];

@NgModule({
  imports: [
    RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules, enableTracing: false })
  ],
  exports: [RouterModule]
})

ProfileComponent.ts

this.router.navigate(['email'], { relativeTo:this.route });

这会将 url 更改为 profile/email 但打开 ProductDetailsComponent 而不是 ChangeEmailComponent

在 profilecomponent 中放置一个路由器出口或将您的路由更改为:-

const routes: Routes = [
  { path: '', redirectTo: '/home', pathMatch: 'full'},
  { path: 'home', component: HomeComponent },
  { path:':productName/:productId', component: ProductDetailsComponent },
  { path:'perfil', children: [
    { path: '', component: ProfileComponent},
    { path: 'email', component: ChangeEmailComponent },
  ]},
  { path: '404', component: NotFoundComponent },
  { path: '**', redirectTo: '/404'}
];

有关解释,请参阅:- https://medium.com/@aakashgarg19/the-art-of-nested-router-outlets-in-angular-dafb38245a30

尝试为您的产品路线添加前缀:

来自

{ path:':productName/:productId', component: ProductDetailsComponent },

{ path:'product/:productName/:productId', component: ProductDetailsComponent },

上面提到的解决方案,必须结合两者

  const routes: Routes = [
      { path: '', redirectTo: '/home', pathMatch: 'full'},
      { path: 'home', component: HomeComponent },
      { path:'product/:productName/:productId', component: ProductDetailsComponent },
      { path:'perfil', children: [
        { path: '', component: ProfileComponent},
        { path: 'email', component: ChangeEmailComponent },
      ]},
      { path: '404', component: NotFoundComponent },
      { path: '**', redirectTo: '/404'}
];