簡體   English   中英

我需要使用組件 class 中填充的循環將 object 數組動態分配給 angular 中的圖像輪播容器

[英]I need to dynamically allocate an object array to an image carousel container in angular using a loop populated within the component class

我的問題在於我認為濫用圖像輪播 html 代碼結構。 這是我的 Html:

<div id="carousel-trades" class="carousel slide carousel-fade" data-ride="carousel">
  <div class="carousel-inner" role="listbox">
    <div *ngFor="let ytd of yourTrades; let i = index" class="carousel-item {{ (i == 0) ? 'active' : ''}}">
      <img style="width:310px;height:310px" [src]="splitImageString(ytd.tradeUrl)" (click)="pickImageForTrade(yourTradeImage)"
             alt="First slide">
    </div>
  </div>
</div>

此外,由於不在 scope 范圍內,數組“yourTrades”可能未初始化。

組件.ts 文件:

yourTrades: Trade[];

ngOnInit(): void {
this.resetForm();
this.serviceTrade.getUserId()
  .subscribe(data => {

    this.myId = data;

    let yourTrades = new Array();

    for (let i = 0; i < this.trades.length; i++) {
      if (this.myId.userId == this.trades[i].userId) {
        yourTrades.push(this.trades[i]);
      }
    }
    console.log(yourTrades);
  })
}

當我調用 console.log 時,我得到了預期的對象數組,但是當我的輪播呈現時,它返回空。 一定是從“yourTrades”被填充到被 html 使用時可能存在錯誤連接的事實?

將您的旋轉木馬 html 更改為:-

<div id="carousel-trades" class="carousel slide carousel-fade" data-ride="carousel">
  <div class="carousel-inner" role="listbox">
    <div *ngFor="let ytd of yourTrades; let i = index" class="carousel-item" [ngClass]="{'active': i===0}">
      <img style="width:310px;height:310px" [src]="splitImageString(ytd.tradeUrl)" (click)="pickImageForTrade(yourTradeImage)"
             alt="First slide">
    </div>
  </div>
</div>

您沒有將訂閱中的yourTrades變量分配給成員變量。 嘗試以下

yourTrades: Trade[] = [];     // <-- assign empty array

this.serviceTrade.getUserId()
  .subscribe(data => {
    this.myId = data;
    for (let i = 0; i < this.trades.length; i++) {
      if (this.myId.userId == this.trades[i].userId) {
        this.yourTrades.push(this.trades[i]);       // <-- directly push to the member variable
      }
    }
    console.log(this.yourTrades);
  });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM