【问题标题】:How can I overwrite the data of an existing component in Angular?如何覆盖 Angular 中现有组件的数据?
【发布时间】: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;
  }

}

【问题讨论】:

    标签: angular rxjs


    【解决方案1】:

    当您每 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);
    
          })
        }
      }
    

    【讨论】:

    • 这很好用,谢谢。现在唯一的问题是,当页面用新数据刷新时,正在删除的旧数据和正在使用的新数据之间会出现闪烁。无论如何我可以阻止这种眨眼吗?
    • 我认为可以通过加载器来移除blink,之前显示加载器,然后在获取数据后将其移除,我可以认为这样可以提供良好的用户体验。
    • 但是数据每5秒刷新一次,也就是说每5秒闪烁一次。
    • 可能是的,用户可以看到正在更新。
    猜你喜欢
    • 2018-08-25
    • 2018-11-15
    • 2017-04-05
    • 1970-01-01
    • 2016-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多