【发布时间】:2019-07-03 10:47:55
【问题描述】:
我正在尝试编写一个 web 应用程序来监控各种加密货币的价格,作为学习 Angular 的练习。
目前我已经设法每 5 秒从 API 返回值并在屏幕上显示新数据。问题在于,当进行 API 调用时,新数据用于创建新组件。这意味着每 5 秒创建 3 个新组件。相反,我希望现有组件被它们的新值覆盖。
为了能够做到这一点,我觉得我必须先创建组件,而不是使用*ngFor 指令来动态创建它们。但我不太确定我该怎么做。
HomeComponent 模板
<div class="container ticker-row-container">
<div class="row">
<div class="col-12">
<app-ticker-row *ngFor="let detail of cryptoDetails" [cryptoDetail]="detail"></app-ticker-row>
</div>
</div>
</div>
HomeComponent 类
export class HomeComponent implements OnInit {
cryptos: string[] = ['bitcoin', 'ethereum', 'litecoin']
cryptoDetails: CryptoDetail[];
constructor(private cryptoService: CryptoService) { }
ngOnInit() {
this.cryptoDetails = new Array();
this.getCryptoData();
const source = interval(5000).subscribe(val => this.getCryptoData());
}
getCryptoData(){
console.log("get crypto")
for(let crypto of this.cryptos){
this.cryptoService.getCryptoInfo(crypto).subscribe(res => {
let data = res.data;
let cryptoDetail = new CryptoDetail(data.id, data.rateUsd, data.symbol);
this.cryptoDetails.push(cryptoDetail);
})
}
}
}
TickerRowComponent 模板
<div class="row">
<div class="col-4">{{cryptoDetail.symbol}}</div>
<div class="col-4">{{cryptoDetail.id}}</div>
<div class="col-4">{{cryptoDetail.rate}}</div>
</div>
TickerRowComponent 类
export class TickerRowComponent implements OnInit, OnChanges {
@Input() cryptoDetail: CryptoDetail
currentRate: string;
constructor() { }
ngOnInit() {
this.currentRate = this.cryptoDetail.rate;
}
}
【问题讨论】: