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

Angular #25 - 深入 Service [2]

shutterstock_198004562
  • 在這一篇我們會讓整個系統看起來完整許多:

    • 首先先看到 StocksComponent,其 controller 程式碼如下:

        import { Component, Input } from '@angular/core';
        import { AccountService } from '../services/account.service';
      
        @Component({
          selector: 'app-stocks',
          templateUrl: './stocks.component.html',
          styleUrls: ['./stocks.component.css']
        })
        export class StocksComponent {
          @Input() stocks: any;
      
          constructor(private accountService: AccountService) {}
      
          buy(stock): void {
            this.accountService.purchase(stock);
          }
        }
      • 這個 Component 主要是跟市面上有公開販賣的股票相關
      • 它會從 AppComponent 透過 @Input 取得所有股票的資訊
      • 在建構子注入的 AccountService,主要應用在買股票的方法 buy,看到這個方法直覺就會想到 Template 上可能有個按鈕的 click 事件會跟這個方法綁定,因此我們再來看一下 template
    • StocksComponent 的 Template 如下:

        <clr-datagrid>
          <clr-dg-column [clrDgField]="'symbol'">Symbol</clr-dg-column>
          <clr-dg-column [clrDgField]="'name'">Name</clr-dg-column>
          <clr-dg-column [clrDgField]="'price'">Price</clr-dg-column>
          <clr-dg-column [clrDgField]="'change'">Change</clr-dg-column>
          <clr-dg-column></clr-dg-column>
      
          <clr-dg-row *clrDgItems="let stock of stocks">
            <clr-dg-cell>{{stock.symbol}}</clr-dg-cell>
            <clr-dg-cell>{{stock.name}}</clr-dg-cell>
            <clr-dg-cell>{{stock.price | currency:'USD':'symbol':'.2'}}</clr-dg-cell>
            <clr-dg-cell>{{stock.change | currency:'USD':'symbol':'.2'}}</clr-dg-cell>
            <clr-dg-cell class="btn-cell"><button class="btn btn-sm" (click)="buy(stock)">Buy</button></clr-dg-cell>
          </clr-dg-row>
      
          <clr-dg-footer>
            {{pagination.firstItem + 1}} - {{pagination.lastItem + 1}} of {{total}} stocks
            <clr-dg-pagination #pagination [clrDgPageSize]="10"></clr-dg-pagination>
          </clr-dg-footer>
        </clr-datagrid>
      • 沒看過的 Tag 對吧,這是 Clarity UI 的 Grid ,主要分成三塊:
        • 最上面的標題欄
        • 中間的資料列
        • 最下方的分頁標籤
      • 原則上使用方式就跟 Angular 原生的 Component 與 Directive 差不多,這裡就不再贅述
      • 其中我們最關注的資料來源 stocks 是構成整個 template 的主軸,再來就是資料列的最後一欄有顆按鈕綁定了 click 事件
  • 有股票一覽表,自然有持有股票的表格,就是 InvestmentComponent

    • 跟 StockComponent 幾乎一樣,差異在:

      • 顯示的是使用者持有的股票

      • 為了要使用 AccountService,要實作其 controller 如下:

          import { Component, DoCheck } from '@angular/core';
          import { AccountService } from '../services/account.service';
        
          @Component({
            selector: 'app-investments',
            templateUrl: './investments.component.html',
            styleUrls: ['./investments.component.css']
          })
          export class InvestmentsComponent implements DoCheck {
            cost: number = 0;
            value: number = 0;
            change: number = 0;
            stocks: any = [];
            length: number = 0;
        
            constructor(private accountService: AccountService) { }
        
            sell(index): void {
              this.accountService.sell(index);
            }
        
            ngDoCheck() {
              if (this.accountService.stocks.length !== this.stocks.length) {
                this.stocks = this.accountService.stocks;
              }
              if (this.cost !== this.accountService.cost || this.value !== this.
                accountService.value) {
                this.cost = this.accountService.cost;
                this.value = this.accountService.value;
                this.change = this.accountService.value - this.accountService.cost;
              }
            }
          }
        • 這個 controller 有幾個重點:
          • 它的資料來源不是從 @Input 來的,那是怎麼取得的?答案就在它實作的介面 DoCheck
          • 承上,如果對前面的 LifeCycle Hook 還有點印象的話,就會記得 DoCheck 是每一次 Change Detection 被觸發的時候會呼叫的
          • 再來我們看 ngDoCheck 的方法內容,就是比對自己維護的 cost/value/change/stocks 與注入的 AccountService 中的值是否一樣來變動其屬性值
  • 在完成上面的兩個 Component 後,我們就可以看到全貌了

    • 先到 app.component.html
      • 將原本被註解掉的 <nav-header> 還原
      • 再來 ng serve 啟動系統
      • 可以看到畫面如下:
      • 細部的動畫或是其他的元件暫時不在此說明,只要確定買賣股票的功能跟 人生重來槍(reset) 可以正常擊發就好
  • 小結:

    • 這一篇跟前一篇我們回顧了 Angular 的 service:
      • 它如何被定義
      • 它如何被使用(注入)
      • 下一篇將針對其相依注入的原理作深入探討
Angular #26 - 深入 Service [3]
Angular #24 - 深入 Service [1]

相關文章

 

評論

尚無評論
已經注冊了? 這裡登入
Guest
2025/05/22, 週四

Captcha 圖像