選單
GSS 技術部落格
在這個園地裡我們將從技術、專案管理、客戶對談面和大家分享我們多年的經驗,希望大家不管是喜歡或是有意見,都可以回饋給我們,讓我們有機會和大家對話並一起成長!
若有任何問題請來信:gss_crm@gss.com.tw
4 分鐘閱讀時間 (714 個字)

Angular #8 - 初見 Angular Routing

shutterstock_198004562
  • 在前一篇中我們將原本在 AppComponent 的邏輯抽到了 DashboardComponent,同時定義了一個 ManageComponent 來管理要維護的股票代碼

    • 如果各位有曾經看過 SPA(Single Page Application) 這個名詞的話,或許可能會有以下的疑問:

      • Component 之間要怎麼切換顯示?
      • ManageComponent 並不在 AppComponent 內,在沒有父子關係的情況下要如何才能被 Render?
    • 這就是 Angular Routing 要進場的時候了

      • 什麼是 Angular Routing?

        • 講白了就是透過 URL 中不同的 path 載入不同的 Component
        • 而要讓這個機制能夠運作,我們必須定義所謂的 router outlet,也就是定義在哪 render
      • 一開始透過 ng new 建立專案的時候其實 CLI 就有問我們需不需要建立 Routing 的機制 ,如果當初選 yes,會產出一個 app-routing.module.ts

        • 它主要就是在定義 Routing 的規則的,但並非唯一一個可以定義的地方 (後續會再提到)

        • 打開 app-routing.module.ts 並填入以下內容:

            import { NgModule } from '@angular/core';
            import { Routes, RouterModule } from '@angular/router';
          
            import { DashboardComponent } from './components/dashboard/dashboard.component';
            import { ManageComponent } from './components/manage/manage.component';
          
            const routes: Routes = [
              { path: '', component: DashboardComponent},
              { path: 'manage', component: ManageComponent}
            ];
          
            @NgModule({
              imports: [RouterModule.forRoot(routes)],
              exports: [RouterModule]
            })
            export class AppRoutingModule { }
          • 首先要引用 Routes, RouterModule 以及會用到的 Component(以此篇為例是 DashboardComponentManageComponent)
          • 接著要定義 routes
            • 它是一個物件陣列,最單純的情況下只要放 pathcomponent,主要的作用是在 URL 上看到什麼路徑會需要初始化什麼 component
          • 最後要在 imports 陣列中呼叫 Routes 的 forRoot,才會完成整個路由的後端設定`
        • 調整 app.module.ts,在 import 的部份加上 app-routing.module.ts,這樣在 bootstrap 的時候才會把 路由的規則也加進來

      • 在定義好 Routing 的規則之後,還要在頁面上呈現

        • Component 在不同路由的顯示,要透過一個 <router-outlet></router-outlet> 來定義在哪邊長出這些東西
        • 除此之外,頁面上的連結也要搭配 [routerLink] 來作導頁
  • 來作個總結:

    • Angular app 就是一個根 Component 加上很多的 Child Components(概念上)
      • 根 Component 在頁面載入時就會被 bootstrap
      • Bootstrap 的流程忘記的話可以去看一下第三篇
    • ComponentES6 的規範中的 class 以 @Component 裝飾的結果
      • 這個 Decorator 告訴我們這如何使用它(selector)
      • 承上,也告訴我們它如何呈現(html),以及它套用的樣式(style)
    • Service 也是 ES6 中所定義的 module
      • 它應該是要 portable 的
      • 意思就是只要是 ES6 的類別,都可以使用,並不限定在 Angular
    • Directive 是一種屬性用來動態修改 template 的結構, e.g. *ngIf, *ngFor
    • Angular 有許多內建支援 form 的功能, 像是驗證,事件綁定與分組
    • Routing 就是 path 對應到 component 的 mapping
  • 到此篇為止的知識已經足以寫一個基本又不單純的 Angular App

    • 當然後面還會再更深入談以下的議題:
      • Components
      • Services
      • Routing
      • Forms
      • Testing
      • Production
Angular #9 - 深入淺出 Angular [1]
Angular # 7 - 初見 Angular Forms

相關文章

 

評論

尚無評論
已經注冊了? 這裡登入
Guest
2024/05/04, 週六

Captcha 圖像