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

时间:2019-01-26 19:06:31

标签: angular routing angular-router

我想创建一个嵌套的路线电影/:id。但是,使用我当前的配置,当用户导航到movie / 1时,总是呈现父组件。我需要MovieDetailComponent才能在movie / 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'}
];
`

2 个答案:

答案 0 :(得分:3)

如果您的路由包含一个组件和一个子字段,则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'}
];

答案 1 :(得分:0)

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