我在Angular 5中遇到问题。
我想支持以下网址
这个有效:
/post
这个没有,它将我重定向到我的NotFoundComopnent
/post/test-post-title
我的AppRoutingModule
export const routes: Routes = [
{ path: 'post', loadChildren: 'app/feature/post/post.module#PostModule' },
{ path: '**', component: NotFoundComponent },
];
export class AppRoutingModule { }
我的PostRoutingModule:
const routes: Routes = [
{
path: '',
component: PostHomeComponent,
children: [
{
path: ':slug', component: PostDetailComponent
}
]
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class PostRoutingModule { }
更新以显示PostDetailComponent
export class PostDetailComponentimplements OnInit {
constructor(
private route: ActivatedRoute
) {}
ngOnInit() {
const id = +this.route.snapshot.paramMap.get('slug');
console.log(id)
}
}
答案 0 :(得分:5)
使用"孩子定义子路线时:[{...}]"和PostRoutingModule一样,你必须在PostHomeComponent中有一个路由器插座,才能注入这个子组件。
换句话说,如果组件B是组件A的子组件,则您无法将它们注入到应用程序级别的同一路由器插座中。
要么在PostHomeComponent中有一个路由器插座 - 这可能是您想要的,也可能不是您想要的,因为您最终会同时显示父组件和子组件。
或者,将您的路线更改为:
const routes: Routes = [
{
path: '',
component: PostHomeComponent
},
{
path: ':slug', component: PostDetailComponent
}
];
答案 1 :(得分:0)
const routes: Routes = [
{ path: '', redirectTo: '', pathMatch: 'full'},
{ path: 'post', component: 'PostHomeComponent'},
children: [
{ path: 'test-post-title', component: 'PostDetailComponent'},
],
{ path: '**', component: NotFoundComponent },
];
但请记住,在您的父组件(即您的情况下的PostHomeComponent)和<router-outlet>
角内部包括一个<router-outlet>
会加载您的子组件,即PostDetailComponent。希望对您有帮助。......如果仍然不清楚,请检查此链接Introduction to Angular Routing。它包括