首页 > 解决方案 > 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。

标签: angularspring

解决方案


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)
        );
}

推荐阅读