我有这样的父路线
export const routes: Routes = [
{ path: '', redirectTo: 'posts', pathMatch: 'full' },
{ path: 'posts', component: PostsComponent, children: PostRoutes }
];
现在孩子的路线是这样的
export const PostRoutes = [
{ path: '', component: PostsListComponent },
{ path: ':id', component: PostDetailComponent }
]
现在,当我导航到localhost:4200
或localhost:4200/posts
时,它选择第一个子路线并渲染PostsListComponent
,其中列出了所有帖子。当我点击单个帖子然后它带我到URL localhost:4200/posts/1
并呈现PostListComponent
列出一个单独的帖子和它的详细信息。
现在的问题是当我用这条路线localhost:4200/posts/1
重新加载页面时,它带我到基本网址localhost:4200
并给我错误,无法读取未定义的属性comments
,因为帖子有很多评论。
问题是因为在重新加载页面时,posts array
是null
,所以它无法从URL中选择带有postId的帖子。所以它给了我上面的错误。
那么如何在重新加载页面时管理它,首先必须加载所有帖子。
下面是我的posts.component.html
<div class="container">
<router-outlet></router-outlet>
</div>
下面是我的posts-list.component.html
<div [routerLink]="['/posts', post.id]" *ngFor="let post of posts$ | async">
<h3>{{post.description}}</h3>
</div>
对依赖于要加载的数据的路由使用保护,只有在数据可用后才能完成。
有关文档,请参阅https://angular.io/docs/ts/latest/guide/router.html#!#guards。