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

Angular #6 - Services and Components[3]

shutterstock_198004562
  • 前一篇我們在 AppComponent 中顯示了單筆的股票資訊

    • 在這一篇,我們要讓兩者更相容

      • 首先我們要建立一個 DashboardComponent

      • 建立的語法如下:

          ng g c components/dashboard
        • g 是 generate 的縮寫
        • c 是 component 的縮寫
        • 同樣的 s 是 service 的縮寫,d 是 directive 的縮寫 ... 等
      • 接著要從 AppComponent 把東西搬到 DashboardCopmonent

        • 首先把 app.component.html 調整如下:

            <main class="mdl-layout__content" style="padding: 20px">
                <dashboard></dashboard>
            </main>
          • 調完之後畫面上應該只會呈現 Dashboard works ..之類的訊息
        • 再來要把 AppComponent 中的邏輯抽出

            import { Component } from '@angular/core';
            @Component({
              selector: 'app-root',
              templateUrl: './app.component.html',
              styleUrls: ['./app.component.css']
            })
            export class AppComponent {}
          • 乾淨溜溜,啥也不剩
          • 這時候 compiler 應該各種報錯,但我們先無視它
        • 接著把剛 AppComponent 抽出的部份放到 DashboardComponent

            import { Component, OnInit } from '@angular/core';
            import { StocksService, StockInterface } from '../../services/stocks.service';
          
            @Component({
              selector: 'dashboard',
              templateUrl: './dashboard.component.html',
              styleUrls: ['./dashboard.component.css']
            })
            // Implements an interface OnInit
            export class DashboardComponent implements OnInit {
          
              stocks: Array<StockInterface>;
              symbols: Array<string>;
          
              constructor(private stockService: StocksService) {
                this.symbols = stockService.get();
              }
          
              // Enforced to implement this method ngOnInit
              ngOnInit(): void {
                // Loads stock information from remote service
                this.stockService
                    .load(this.symbols)
                    .subscribe(stocks => {
                      this.stocks = stocks;
                    });
              }
          
            }
          • StockInterface 派上用場了,這個 component 會維護一個陣列的股票資訊
          • 承上,除了上面的 interface 之外還會維護一個股票代碼的陣列(e.g. APPL, GOOG)
          • 這邊可以看到 implements OnInit,這是 Angular Component 生命週期相關的介面,代表 Component 在初始化的時候要做一些事,這些事會強制定義在 ngOnInit 這個方法內(介面的約束力)
          • 我們又看到建構子中注入 StockService 了,而且在 ngOnInit 呼叫其 load,並 subscribe
            • 這邊特別提一下,stockService 在注入的同時變成這個 component 的屬性之一,而且這個設定是同步的(早就在 app.module.ts 產出實體了)
            • 還記得 load 回傳的是一個 Observable 嗎?
            • subscribe 才會真的發出 request,並在 response 的時候設定好這個 component 要維護的股票代碼(所以這裡是非同步喔)
        • 處理好 Controller 的部份之後,自然是要在 View 中呈現資料,好在 Angular 有很方便的 Directive:

            <div class="mdl-grid">
              <div
                class="mdl-cell mdl-cell--12-col"
                *ngIf="!stocks"
                style="text-align: center"
              >
                Loading
              </div>
              <div class="mdl-cell mdl-cell--3-col" *ngFor="let stock of stocks">
                <summary [stock]="stock"></summary>
              </div>
            </div>
          • 又看見 *ngIf 了,沒有股票資訊就呈現 Loading
          • 出現了一個新的 directive 叫 NgFor,顧名思議就是要用 for 迴圈針對每一支股票 render 出一個 SummaryComponent
          • 等等…你說 stocks 從哪來的?再回去看一下 DashboardComponent 的建構子load 方法
        • 此時的畫面應該就會長出五筆股票資訊如下圖:

          • 如果沒看到畫面代表你有東西漏了,再檢查看看吧!
  • 小結一下

    • 這篇透過新增 DashboardComponent,並搬移了原本放在 AppComponent 的邏輯達到了權責分離
      • 這部份主要透過 ng new 產了新 component
      • 接著把 html/ts 的部份作了對應的移動
      • 此外也用了 *ngFor 這個 Directive,剩下的部份都沒有動喔
×
Stay Informed

When you subscribe to the blog, we will send you an e-mail when there are new updates on the site so you wouldn't miss them.

jQuery with typescript
Angular #5 - Services and Components[2]

相關文章

 

評論

尚無評論
已經注冊了? 這裡登入
2025年12月14日, 星期日

Captcha 圖像