前一篇我們在 AppComponent 中顯示了單筆的股票資訊
在這一篇,我們要讓兩者更相容
首先我們要建立一個 DashboardComponent
建立的語法如下:
ng g c components/dashboard
接著要從 AppComponent 把東西搬到 DashboardCopmonent
首先把 app.component.html 調整如下:
<main class="mdl-layout__content" style="padding: 20px">
<dashboard></dashboard>
</main>
再來要把 AppComponent 中的邏輯抽出
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {}
接著把剛 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;
});
}
}
處理好 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>
此時的畫面應該就會長出五筆股票資訊如下圖: 
小結一下
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.
評論