Issue
I am having trouble routing in Angular 5.
I would like to support the following URL's
This one works:
/post
This one doesn't, it redirects me to my NotFoundComopnent
/post/test-post-title
My AppRoutingModule
export const routes: Routes = [
{ path: 'post', loadChildren: 'app/feature/post/post.module#PostModule' },
{ path: '**', component: NotFoundComponent },
];
export class AppRoutingModule { }
My PostRoutingModule:
const routes: Routes = [
{
path: '',
component: PostHomeComponent,
children: [
{
path: ':slug', component: PostDetailComponent
}
]
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class PostRoutingModule { }
Updated to show the PostDetailComponent
export class PostDetailComponentimplements OnInit {
constructor(
private route: ActivatedRoute
) {}
ngOnInit() {
const id = +this.route.snapshot.paramMap.get('slug');
console.log(id)
}
}
Solution
When you define a child route using "children: [{ ... }]" as in your PostRoutingModule, you must have a router outlet inside your PostHomeComponent for this child component to be injected in.
In other words, if Component B is child of Component A, you can't expect to inject them both into the same router outlet that you have on app level.
Either, have a router outlet inside PostHomeComponent - this may or may not be what you want as you would end up displaying both Parent and Child components at the same time.
Or, change your routes to this:
const routes: Routes = [
{
path: '',
component: PostHomeComponent
},
{
path: ':slug', component: PostDetailComponent
}
];
Answered By - Uğur Dinç
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.