Angular 5中的子路由无法正常工作

Rob*_*lls 3 angular

我在Angular 5中遇到麻烦.

我想支持以下网址

这个工作:

/post  
Run Code Online (Sandbox Code Playgroud)

这个没有,它将我重定向到我的NotFoundComopnent

/post/test-post-title
Run Code Online (Sandbox Code Playgroud)

我的AppRoutingModule

export const routes: Routes = [
    { path: 'post', loadChildren: 'app/feature/post/post.module#PostModule' },
    { path: '**', component: NotFoundComponent },

];

export class AppRoutingModule { }
Run Code Online (Sandbox Code Playgroud)

我的PostRoutingModule:

const routes: Routes = [
    {
        path: '',
        component: PostHomeComponent,

        children: [
            { 
                path: ':slug', component: PostDetailComponent 
            }
        ]
    }
];

@NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule]
})

export class PostRoutingModule { }
Run Code Online (Sandbox Code Playgroud)

更新以显示PostDetailComponent

export class PostDetailComponentimplements OnInit {

  constructor(
    private route: ActivatedRoute
  ) {}

  ngOnInit() {
    const id = +this.route.snapshot.paramMap.get('slug');
    console.log(id)
  }
Run Code Online (Sandbox Code Playgroud)

}

Uğu*_*inç 6

当您使用PostRoutingModule中的"children:[{...}]"定义子路由时,您必须在PostHomeComponent中有一个路由器插座,以便为此子组件注入.

换句话说,如果组件B是组件A的子组件,则不能指望将它们注入到应用程序级别的同一路由器插座中.

或者,在PostHomeComponent中有一个路由器插座 - 这可能是您想要的,也可能不是您想要的,因为您最终会同时显示父组件和子组件.

或者,将您的路线更改为:

const routes: Routes = [
    {
        path: '',
        component: PostHomeComponent
    },
    { 
        path: ':slug', component: PostDetailComponent 
    }

];
Run Code Online (Sandbox Code Playgroud)