【问题标题】:How to handle routes on page refresh in angular2如何在angular2中处理页面刷新时的路由
【发布时间】: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:4200localhost:4200/posts 时,它会选择第一个子路由并渲染PostsListComponent,它列出了所有帖子。当我单击单个帖子时,它会将我带到 URL localhost:4200/posts/1 并呈现 PostListComponent,其中列出了单个帖子及其详细信息。

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

问题是因为在重新加载页面时,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】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-06
      • 1970-01-01
      • 2022-01-05
      • 2016-04-23
      • 1970-01-01
      • 2019-01-12
      • 2021-06-11
      • 1970-01-01
      相关资源
      最近更新 更多