0

我的问题在于我认为对图像轮播 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>

此外,由于超出范围,数组“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使用时可能存在错误连接的事实?

4

2 回答 2

0

您没有将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);
  });
}
于 2020-06-12T08:14:56.893 回答
0

将您的轮播 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>
于 2020-06-12T08:00:15.487 回答