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

问题描述 投票:1回答:1

我有这样的父路线

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:4200localhost:4200/posts时,它选择第一个子路线并渲染PostsListComponent,其中列出了所有帖子。当我点击单个帖子然后它带我到URL localhost:4200/posts/1并呈现PostListComponent列出一个单独的帖子和它的详细信息。

现在的问题是当我用这条路线localhost:4200/posts/1重新加载页面时,它带我到基本网址localhost:4200并给我错误,无法读取未定义的属性comments,因为帖子有很多评论。

问题是因为在重新加载页面时,posts arraynull,所以它无法从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>
angular angular2-routing
1个回答
1
投票

对依赖于要加载的数据的路由使用保护,只有在数据可用后才能完成。

有关文档,请参阅https://angular.io/docs/ts/latest/guide/router.html#!#guards

© www.soinside.com 2019 - 2024. All rights reserved.