2016-12-02 24 views
1

在頁面刷新的路線我有這樣如何處理angular2

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,因爲帖子有很多評論。

問題是,因爲重新加載頁面,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> 

回答