前一篇主要針對 Service 作了以下處理:
首先當然是定義它長怎樣,其中包含:
那麼定義完之後,我們也在 app.module.ts import 並註冊了這個 Service,想必接下來就是要使用它了
在使用它之前我們必須先建立一個 Component,用來顯示一張股票的基本資訊
這個 Component 存在的目的是:
建立 Component 的語法如下:
ng generate component componenets/summary
此時在 src/app/components/summary 這個目錄底下會產出 SummaryComponent 相關的檔案,理論上有4個,分別是:
接著在 summary.component.html 中填入以下內容
<div
class="mdl-card stock-card mdl-shadow--2dp"
[ngClass]="{ increase: isPositive(), decrease: isNegative() }"
style="width: 100%"
>
<span>
<div class="mdl-card__title">
<h4 style="color: #fff; margin: 0">
{{ stock?.symbol?.toUpperCase() }}<br />
{{ stock?.lastTradePriceOnly | currency: "USD":"symbol":".2" }}<br />
{{ stock?.change | currency: "USD":"symbol":".2" }} ({{
stock?.changeInPercent | percent: ".2"
}})
</h4>
</div>
</span>
</div>
接著在 controller 中輸入以下內容:
import { Component, Input, OnInit } from '@angular/core';
@Component({
selector: 'summary',
templateUrl: './summary.component.html',
styleUrls: ['./summary.component.css']
})
export class SummaryComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
@Input() stock: any;
isNegative() {
return this.stock && this.stock.change < 0;
}
isPositive() {
return this.stock && this.stock.change > 0;
}
}
<summary [stock]="stockData"></summary>
再來我們在 summary.component.css 檔中填入以下內容:
:host .stock-card {
background: #333333;
}
:host .stock-card.increase {
background: #558B2F;
color: #fff;
}
:host .stock-card.decrease {
background: #C62828;
color: #fff;
}
我們終於可以在 AppComponent 裡使用 StockService 了
app.component.ts 的內容如下
import { Component } from '@angular/core';
import { StocksService, StockInterface } from './services/stocks.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'stocks';
stocks: Array<StockInterface>;
constructor(private service: StocksService) {
service.load(['AAPL']).subscribe(
(stocks) => {
this.stocks = stocks;
}
)
}
}
Service 都架好之後,來處理 View 的部份吧
<div class="mdl-layout mdl-js-layout mdl-layout--fixed-header">
<header class="mdl-layout__header">
<div class="mdl-layout__header-row">
<span class="mdl-layout-title">Stock Tracker</span>
<div class="mdl-layout-spacer"></div>
<nav class="mdl-navigation mdl-layout--large-screen-only">
<a class="mdl-navigation__link">Dashboard</a>
<a class="mdl-navigation__link">Manage</a>
</nav>
</div>
</header>
<main class="mdl-layout__content" style="padding: 20px" *ngIf="stocks">
<summary [stock]="stocks[0]"></summary>
</main>
</div>
此時看到的畫面應該如下圖:
小結一下: