如何在angular2中处理页面刷新时的路由

如何在angular2中处理页面刷新时的路由,angular,angular2-routing,Angular,Angular2 Routing,我有这样的家长路线 export const routes: Routes = [ { path: '', redirectTo: 'posts', pathMatch: 'full' }, { path: 'posts', component: PostsComponent, children: PostRoutes } ]; 现在孩子们的路线是这样的 export const PostRoutes = [ { path: '', component: PostsListComp

我有这样的家长路线

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
,其中列出了所有帖子。当我单击single post时,它会将我带到URL
localhost:4200/posts/1
并呈现
PostListComponent
,其中列出了一篇文章及其详细信息

现在的问题是,当我使用此路由重新加载页面时,它会将我带到基本URL
localhost:4200
,并给我一个错误,即无法读取未定义的属性
comments
,因为posts有许多注释

问题是,在重新加载页面时,
posts数组
null
,因此无法从URL中选择带有postId的帖子。所以它给了我以上的错误

因此,如何管理在重新加载页面时,首先必须加载所有帖子

下面是我的
posts.component.html

<div class="container">
  <router-outlet></router-outlet>
</div>
 <div [routerLink]="['/posts', post.id]" *ngFor="let post of posts$ | async">
   <h3>{{post.description}}</h3>
 </div>

对依赖于要加载的数据的路由使用防护,该防护仅在数据可用后完成

有关文档,请参阅