【发布时间】:2017-04-17 01:32:20
【问题描述】:
我有这样的父路由
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 重新加载页面时,它会将我带到基本 URL localhost:4200 并给出错误,即无法读取未定义的属性 comments,因为帖子有很多 cmets。
问题是因为在重新加载页面时,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>
【问题讨论】: