繁体   English   中英

角路由不渲染子组件,而是渲染父组件

[英]Angular Routes not rendering child components, instead render parent component

我想创建一个嵌套的路线movies/:id但是使用我当前的配置,当用户导航到movies/1 ,始终会渲染父组件。 我需要MovieDetailComponent才能在movies/1 URL上呈现。 这是我的配置:

const routes: Routes = [{
    path: '',
    component: HomeView
  },
  {
    path: 'movies',
    component: MoviesView,
    children: [{
      path: ':id',
      component: MovieDetailComponent
    }]
  },
  {
    path: 'not-found',
    component: PageNotFoundComponent,
    pathMatch: 'full'
  },
  {
    path: '**',
    redirectTo: 'not-found'
  }
];

我试过pathMatch: 'full'添加到父组件,然后再添加子组件,然后再添加两者。 当我将pathMach: 'full'添加到父组件时,子URL甚至都不会被命中,当我将pathMatch: 'full'仅添加到子组件时,即使URL是/movies/:id为什么会发生这种情况?

当我将子路径移动到其自己的路径中时(未嵌套),该组件将正确呈现。

const routes: Routes = [{
    path: '',
    component: HomeView
  },
  {
    path: 'movies',
    component: MoviesView
  },
  {
    path: 'movies:id',
    component: MovieDetailComponent
  } {
    path: 'not-found',
    component: PageNotFoundComponent,
    pathMatch: 'full'
  },
  {
    path: '**',
    redirectTo: 'not-found'
  }
];

如果您的路由包含一个组件和一个子字段,则Angular将使用该组件的路由器出口放置子组件DOM。 因此,在您的情况下, MoviesView组件中应具有路由器插座:

<router-outlet></router-outlet>

如果要在看moviesmovies/:id时有不同的视图,则需要使用第二种方法。 如果您现在或将来需要在电影路线下有一条以上的额外路线,我更愿意将其写为

const routes: Routes = [
  { path: '', component: HomeView },  
  { path: 'movies',
    children: [
    { path: '', component: MoviesView }
    { path: ':id', component: MovieDetailComponent }
  ]},
  { path: 'not-found', component: PageNotFoundComponent, pathMatch: 'full' },
  { path: '**', redirectTo: 'not-found'}
];

另外,如果您不需要movies路线(没有ID),也可以执行以下操作:

const routes: Routes = [
  { path: '', component: HomeView },  
  { path: 'movies',
    children: [
    { path: ':id', component: MovieDetailComponent }
  ]},
  { path: 'not-found', component: PageNotFoundComponent, pathMatch: 'full' },
  { path: '**', redirectTo: 'not-found'}
];

检查您的<router-outlet>指令, MoviesView组件内部必须有一个。 希望能有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM