首页 > 解决方案 > 在 Angular 中使用 Observables 显示数据时出错

问题描述

我的 Angular 项目中有这项服务

getOfertas(): Observable<Oferta[]> {
return this.http.get<Oferta[]>(`${this.urlWebAPI}/ofertas`)
  .pipe(
    tap(data=>console.log('OfertasService-get(): ', data)
    ),
    catchError(this.handleError)
  )

}

我在 Angular Component.ts 中使用的

ofertas:Oferta[]=[];

ngOnInit(): void {
 this.dataService.getOfertas()
.pipe(
  tap(item=>console.log(item))
 )
.subscribe(
  data=>{
    this.ofertas=data;
    this.ofertasOriginal=this.ofertas;
  }
 )
,err=>console.log(err),
()=>{};
}
}

我想在这个 Component.html 中的表格中查看结果

<div class='table-responsive'>
      <table class='table'>
        <thead>
          <tr>
            <th>Id</th>
            <th>Id Presentada</th>
            <th>Descripción</th>
            <th>Organismo</th>
            <th>Fª Presentación</th>
            <th>Presupuesto</th>
          </tr>
        </thead>
        <tbody>
          <tr *ngFor="let oferta of ofertas; let index=index">
            <td>{{oferta.id}}</td>
            <td>{{oferta.idPresentada}}</td>
            <td>{{oferta.descripcion}}</td>
            <td>{{oferta.id}}</td>
            <td>{{oferta.fechaPresentacionFulcrum}}</td>
            <td>{{oferta.id}}</td>
          </tr>
        </tbody>
      </table>
    </div>

但是我使用从 ASP.NEt Core Web API 获得的数据在控制台中得到了这个结果,但是显示了错误

错误

在我的 Web API 中,当我调试时,我看到返回了这个结果。

控制器

即 Oferta 对象列表

但是在 Angular 中,我得到了一个奇怪的对象

{$id:
 $values:[]
}

但是如果我使用这个 ~$values 进行迭代,我仍然什么也看不到

<tr *ngFor="let oferta of ofertas.$values; let index=index">

如果我尝试分配这个

价值观

我想使用我的 ofertas 变量 ofertas:Oferta[]=[]

这里我有一个同样问题的例子;https://stackblitz.com/edit/angular-ivy-ymtnrw?file=src/app/app.component.html

请问有什么想法吗?

谢谢

标签: angularasp.net-coreasp.net-web-api

解决方案


响应本身不是一个数组,而是包含一个。

您需要将模板更改为

<tr *ngFor="let oferta of ofertas.$values; let index=index">

推荐阅读