# Day25 【牙起來】 路由設定(Router) - Angular
> 關於`RxJS`後續部分的深入
>
> 關於應用想到了幾個實際運用場合
> 但小弟還需花點時間建設環境,未來幾天會再把文章補上
>
> 今天先來談談路由
`Router` 在Angular裡面可以到處加,只要有**模組**的地方就可以有**路由**
路由是一支`.ts`檔程式,檔案名稱為 `...routing.module.ts`
### 由`ng-cli`建立路由
新建專案時產生路由
> ng new project04 --routing
<!--
// TODO先別提巢狀路由
新建模組時產生路由
> ng g m test --routing
-->
也可以自己手動新增 `...routing.module.ts` 的檔案
## 手動新增 routing
在`src/app`底下(與`app.module.ts`同層資料夾)
新增 `app-routing.module.ts`
```typescript=
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component';
import { StoreComponent } from './store/store.component';
import { RoleComponent } from './role/role.component';
const routes: Routes = [
// { path: '', component: AppComponent },
{ path: 'store', component: StoreComponent },
{ path: 'role', component: RoleComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {
}
```
在 `app.component.html` 新增
```html=
<h1>更改網址後綴為 /store 或 /role</h1>
<router-outlet></router-outlet>
```
最後在`app.module.ts`中引入`RouterOutlet`, `AppRoutingModule`
```typescript=
import { RouterOutlet } from '@angular/router';
...
@NgModule({
...
imports: [
BrowserModule,
RouterOutlet,
AppRoutingModule
],
...
```
此時的 `<router-outlet>` 代表的就是 **會變動的Router** 囉
這玩意就是你定義在`routing.module.ts`的Routes對應到的物件
http://localhost:4200/role
http://localhost:4200/store
> 可以把`app-routing.module.ts`中註解掉的`{ path: '', component: AppComponent },`
> 這一行補上去試試效果,會發現首頁會出現了兩次相同的元素
>
> 因為`Angular`啟動預設執行一次`AppComponent`、Routes發現網址進來比對`<router-outlet>`結果又執行一次`AppComponent`,造成非預期的效果
## 透過 routerLink 切換分頁
修改 `app.component.html`
```html=
<h1>更改網址後綴為 /store 或 /role</h1>
<router-outlet></router-outlet>
<button routerLink="store">點我進store</button>
<a routerLink="role">點我進role</a>
<br><br><br>
<div routerLink="">其實點我也能有效果,回首頁</div>
```
> 此時可以在元件內加上`ngOnDestroy()`
> 測試前面提到的生命週期物件摧毀時的效果
>
> ```typescript=
> ngOnDestroy(): void {
> console.log('==== ngOnDestroy ====')
> alert('確定要切換分頁嗎?')
>}
> ```
### `[routerLink]` 與 routerLink 有何差別
* `routerLink` 是屬性(Attribute)
* `[routerLink]` 是屬性繫結(Property),可帶入成員
```html=
<h1>更改網址後綴為 /store 或 /role</h1>
<router-outlet></router-outlet>
<button [routerLink]="pages[0]">點我進store</button>
<a [routerLink]="'role'">點我進role</a>
<br><br><br>
<div [routerLink]="''">其實點我也能有效果,回首頁</div>
```
在`app.component.ts`新增`router`成員(Member)
```typescript=
export class AppComponent {
title = 'project04';
pages = ['store', 'role']
constructor() {
}
}
```
> 與`style=...`和`[style]='...'`是相同的道理
>
> 你可以兩個同時使用,只是會被前輩敲頭而已