Child Routes
一個 path 對上一個 component 感覺上限制很大(e.g. 很快所有會用的單子的用光了還列不完功能,或是明明四周圍都長得差不多,只是不同的內容,切到不同的 path)
前一篇提到 ForumsComponent 與 ForumComponent(單/複數)
就目前的情境,前者主要列出所有的論壇,而後者列出個別論壇下的所有文章串
承上,我們需要一個 ThreadComponent,而且它四周仍然被 ForumComponent 包圍著
換句話說,path 的變化會如下:
到這裡可能有點暈,不如看個實例好了,調整 一下 forum.component.html:
<header class="header">
<div class="branding">
<span class="title">{{forum?.title}}</span>
</div>
</header>
<router-outlet></router-outlet>
等等,我們似乎還少了一個動作,就是讓 Angular 知道這些規則,所以要調整 forums.module.ts 如下
const forumRoutes: Routes = [
{ path: 'forums', component: ForumsComponent },
{
path: 'forums/:forum_alias',
component: ForumComponent ,
children: [
{ path: '', component: ThreadsComponent },
{ path: ':thread_alias', component: ThreadComponent }
]
}
]
還…還有一件事呢,ThreadsComponent,要知道 URL 的變化才能導到文章串中的特定文章啊!
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { ForumsService } from '../services/forums.service';
import { Thread } from '../services/data';
@Component({
selector: 'app-threads',
templateUrl: './threads.component.html',
styleUrls: ['./threads.component.css']
})
export class ThreadsComponent implements OnInit {
threads: Thread[];
constructor(
private route: ActivatedRoute,
private forumService: ForumsService
) { }
ngOnInit() {
this.route.params.subscribe((params: Params) => {
this.threads = this.forumService.forum(params['forum_alias']).threads;
});
}
}
再來就是調整 threads.component.html
<div class="content-container">
<div class="content-area">
<table class="table" *ngIf="threads">
<tr>
<th>Thread</th>
<th>User</th>
<th>Last Post</th>
<th>Posts</th>
</tr>
<tr *ngFor="let thread of threads" [routerLink]="[thread.alias]">
<td>{{thread.title}}</td>
<td>{{thread.posts[0].username}}</td>
<td>{{thread.posts[0].timestamp | date:'medium'}}</td>
<td>{{thread.posts.length}}</td>
</tr>
</table>
</div>
</div>
現在我們可以選擇 Forum,並從中挑選 Thread,再來就是顯示 Thread 的內容了
先實作 thread.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { ForumsService } from '../services/forums.service';
import { Forum, Thread } from '../services/data';
@Component({
selector: 'app-thread',
templateUrl: './thread.component.html',
styleUrls: ['./thread.component.css']
})
export class ThreadComponent implements OnInit {
forum: Forum;
thread: Thread;
constructor(
private forumsService: ForumsService,
private route: ActivatedRoute) { }
ngOnInit() {
this.route.params.subscribe((params:Params) => {
let forum = this.route.snapshot.parent.params['forum_alias'];
this.thread = this.forumsService.thread(forum, params['thread_alias']);
})
}
}
小結: