如何覆盖Angular中现有组件的数据?

时间:2019-07-03 10:47:55

标签: angular rxjs

我正在尝试编写一个Webapp来监视各种加密货币的价格,以此作为学习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;
  }

}

1 个答案:

答案 0 :(得分:0)

每隔5秒钟订阅一次cryptoService时,您会将新的加密详细信息推送到cryptoDetails数组,这样它将保留先前的加密详细信息以及新的加密详细信息。相反,您可以做的是从getCryptoData函数内的数组中删除先前的值:

getCryptoData(){
    this.cryptoDetails = [];
    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);

      })
    }
  }