![](/img/trans.png)
[英]Angular with child routes load child components below parent component instead of redirecting it to another view
[英]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>
如果要在看movies
和movies/: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.