angular - Angular 前端无法将 json 响应识别为数组
问题描述
在做官方 Angular 教程时,我尝试使用 Spring JPA REST 建立一个真正的后端连接,而不是模拟 Angular“服务器”。REST 端点配置为 PagingAndSortingRepository。这是来自后端的服务器响应。
我尝试将这些数据输入前端,如下所示:
@Injectable({
providedIn: 'root'
})
export class HeroService {
private heroesUrl = 'http://localhost:8080/api/heroes';
constructor(
private http: HttpClient,
private messageService: MessageService ) { }
getHeroes(): Observable<Hero[]> {
// TODO: send the message _after_ fetching the heroes
this.messageService.add('HeroService: fetched heroes');
return this.http.get<Hero[]>(this.heroesUrl); // of(HEROES);
}
HTML 代码:
<h2>My Heroes</h2>
<ul class="list-group">
<li class="list-group-item" *ngFor="let hero of heroes">
<a routerLink="/detail/{{hero.id}}">
<span class="badge badge-dark">{{hero.id}}</span> {{hero.name}}
</a>
</li>
</ul>
此代码产生以下错误:
错误错误:找不到类型为“对象”的不同支持对象“[对象对象]”。NgFor 仅支持绑定到 Iterables,例如 Arrays。
解决方案
HTML 使用异步管道
<table>
<tr *ngFor="let item of getHeroes()|async">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
</tr>
</table>
使用 map 运算符从响应对象中仅获取 heros 属性。
getHeroes(): Observable<Hero[]> {
// TODO: send the message _after_ fetching the heroes
this.messageService.add('HeroService: fetched heroes');
return this.http.get<any>(this.heroesUrl)
.pipe(
map(data => data._embedded.heroes)
);
}
推荐阅读
- javascript - 通过匹配属性值求和值
- assembly - Binary Bomb Lab Phase 6 节点顺序错误
- php - Laravel Passport - 如何创建第一方客户端?
- opencv - 在易受攻击的图像 OpenCV Python 上过滤噪声
- python - 使用“:”将伪代码翻译成python
- javascript - 使用 javascript 在真假之间切换 aria-expanded
- python - 使用 python 仅打印一个 json 键响应的值
- python - 为什么在 Windows 上合并 python 中的文件很慢?
- pandas - GroupBy 两个 DataFrame 的不同列之间的公共值
- python-3.x - 转移文本文件所有权python