亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Angular - *ngFor 僅從數組返回一條記錄,盡管有 12 條記錄可用

Angular - *ngFor 僅從數組返回一條記錄,盡管有 12 條記錄可用

慕無忌1623718 2023-07-28 16:10:06
我在 Angular 中使用 HttpClient 從我使用 SpringBoot 創建的 API 端點檢索數據。我在 Angular 中創建了一個服務來使用數據。我正在將數據打印到控制臺,所以我知道數據正在返回。我試圖將所有輸出傳遞到下拉列表,但盡管使用 *ngFor,但只返回 1 個結果:以下是 HTML 文件中下拉列表的代碼:  <mat-form-field>    <mat-select    placeholder="Select Competition">      <mat-option *ngFor="let comp of competitionsList; let i = index" [value]="comp">        {{ comp[i].name }}      </mat-option>    </mat-select>  </mat-form-field>當我出于測試目的將 [i] 的值更改為或 [11] (數組中的最后一個元素)時,所有數據始終按預期顯示,但當我使用 comp[i].name 時,我會預期所有元素在要返回的數組中,但它只返回第一個元素。我確信這是非常簡單的事情,但我已經研究了很長時間,但仍然不太明白為什么會發生這種情況,所以任何幫助將不勝感激!JSON 響應:[{…}]0:0: {id: 2013, name: "Série A"}1: {id: 2021, name: "Premier League"}2: {id: 2016, name: "Championship"}3: {id: 2001, name: "UEFA Champions League"}4: {id: 2018, name: "European Championship"}5: {id: 2015, name: "Ligue 1"}6: {id: 2002, name: "Bundesliga"}7: {id: 2019, name: "Serie A"}8: {id: 2003, name: "Eredivisie"}9: {id: 2017, name: "Primeira Liga"}10: {id: 2014, name: "Primera Division"}11: {id: 2000, name: "FIFA World Cup"}ident: "competitions"name: "com"**添加附加信息:我已經為 API 返回的值定義了一個接口:export interface Competitions {  id: number;  name: string;}這是我的服務:  retrieveAvailableCompetitions() {    return this.http.get<Competitions>(this.competitionsUrl);  }這是我在 TypeScript 文件中的方法:getCompetitons() {  this.service.retrieveAvailableCompetitions().pipe(    map(responseData => {      const compsList: Competitions[] = [];      for (const key in responseData) {        if (responseData.hasOwnProperty(key)) {          compsList.push({ ...responseData[key], ident: key, name: 'com' });        }      }      return compsList;    })  ).subscribe(    compsList => {      this.competitionsList = compsList;      console.log(compsList);    });  }
查看完整描述

1 回答

?
守著星空守著你

TA貢獻1799條經驗 獲得超8個贊

您在評論中提到了undefined錯誤。這表明您正在嘗試在數據可用之前渲染視圖。在您的元素上使用*ngIf以僅在數據可用時呈現它。


<mat-form-field *ngIf="competitionsList">


</mat-form-field>

當您使用迭代數組時,*ngFor不需要使用索引i。


替換{{ comp[i].name }}為{{ comp.name }}.


那么你的代碼將如下所示


  <mat-form-field *ngIf="competitionsList">

    <mat-select placeholder="Select Competition">

      <mat-option *ngFor="let comp of competitionsList; let i = index" [value]="comp">

        {{ comp.name }}

      </mat-option>

    </mat-select>

  </mat-form-field>

StackBlitz 上的現場演示: https://stackblitz.com/edit/angular-material-with-angular-v5-eukdkc


編輯:您應該將響應格式化compList為competitionsList數組。


將您的subscribe()方法更改為


.subscribe(

   compsList => {

      this.competitionsList = Object.values(compList[0]);

   });


查看完整回答
反對 回復 2023-07-28
  • 1 回答
  • 0 關注
  • 191 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號