我在 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 返回的值定义了一个接口(interface):
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);
});
}
(我知道我应该将大部分代码移至我的服务中,但我计划在解决问题后进行重构)
最佳答案
您在评论中提到了未定义
错误。这表明您正在尝试在数据可用之前渲染 View 。在元素上使用 *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]);
});
关于java - Angular - *ngFor 仅从数组返回一条记录,尽管有 12 条记录可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57939681/