Secondary Routes
又稱 Auxillary routes
講那麼多,該怎麼使用 Secondary Routes? 假設情境是要跟別的 User 聊天
首先,加入以下的程式片段到 app.module.ts
const appRoutes: Routes = [
{ path: 'login', component: LoginComponent },
{ path: 'users', component: ChatListComponent, outlet: 'chat', },
{ path: 'users/:username', component: ChatComponent, outlet: 'chat', },
{ path: '', redirectTo: '/forums', pathMatch: 'full' },
{ path: '**', component: NotFoundComponent },
];
接著要調整一下 app.component.html
<router-outlet name="chat"></router-outlet>
還記得右上角有一個聊天的 icon 嗎? 現在要設定按了它之後會觸發 Angular Routing 的機制
<a class="nav-link nav-icon"
[routerLink]="[{outlets: { chat: ['users']}}]">
<clr-icon shape="talk-bubbles"></clr-icon>
</a>
因為 users 是對應該到 ChatListComponent, 所以接著要調整它的 template
<div class="card">
<div class="card-header">
Select user to chat with
<button aria-label="Close" class="close" type="button" (click)="close()">
<clr-icon aria-hidden="true" shape="close"></clr-icon>
</button>
</div>
<div class="card-block">
<div class="card-text">
<clr-tree-node *ngFor="let user of users" (click)="talkTo = user"><span [class.active]="talkTo == user" class="clr-treenode-link">{{user}}</span></clr-tree-node>
</div>
</div>
<div class="card-footer">
<a class="btn btn-sm btn-link btn-primary" *ngIf="talkTo" [routerLink]="[talkTo]">Start Chat with {{talkTo}}</a>
</div>
</div>
接著要設定 ChatComponent 的 controller,來取得是要跟「誰」對話的資訊
// ...(略)
constructor(
private route: ActivatedRoute,
private router: Router,
private chatBotService: ChatBotService,
private userService: UserService) { }
ngOnInit() {
this.route.params.subscribe((params: Params) => {
this.messages = [];
this.user = this.userService.getUser();
this.guest = params['username'];
})
}
// ...(略)
最後一步就是關閉 Secondary Route(聊天也有結束的一刻),到 ChatListComponent 與 ChatComponent 的 close 方法中實作以下片段
this.router.navigate([{outlets:{ chat: null}}]);
最最最後再補充說明一下,一旦渲染了 Secondary Route,仍然是可以在不同 component 間 route,只要放的是相對路徑,Router 就會懂得前面是什麼東西。
承上,如果在 Secondary Route 裡觸發 routerLink 時放的是絕對路徑(e.g. /forums),那麼異動的只會是 root route,Secondary route 還是維持不變
小結: