【问题标题】:What kind of response is this obtained from EF Core 5 in ASP.NET Core Web API [closed]这是从 ASP.NET Core Web API 中的 EF Core 5 获得的什么样的响应 [关闭]
【发布时间】:2021-12-22 07:28:41
【问题描述】:

我的 ASP.NET Core Web API 控制器中有这个方法

[HttpGet]
public async Task<ActionResult<IEnumerable<Oferta>>> GetOfertas()
{
  return await _context.Ofertas.ToListAsync();
}

然后我的 Angular App 服务中有这个方法

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

}

当我发送这样的请求以从我的组件中填充我的表格时

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


<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.$values; 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>

我什么都没看到

我不明白这种返回的对象

{
 $id:"1"
 $values:Array(16)
}

我希望只有一组 Oferta 对象

有什么想法吗?

谢谢

【问题讨论】:

  • 这根本不是 ASP.NET Core,这就是 Angular 表示数据的方式 - Array(16) 告诉你在 JavaScript 方面
  • 为什么看不到thead的内容?您可以打印 F12 并检查页面中的元素吗?
  • 我的 Web API 仅返回一个数组,Angular 将其转换为具有 2 个属性的对象:$id 和 $values,其中是我想要的数组。所以在我的 *ngFor 指令中,我需要访问第二个属性:let oferta of ofertas.$values 但是虽然在控制台中我看到表中的值没有显示

标签: c# angular asp.net-core entity-framework-core


【解决方案1】:

测试后,您应该使用$.parseJSON(res) 之类的东西来处理响应数据。在角度,也许你可以使用JSON.stringify(string_data);

1.我的测试 api,我们可以看到我这边的响应数据。

2.响应数据是字符串格式,而不是对象。您可以在浏览器中调试器进行检查。

【讨论】:

  • 我需要迭代一个数组而不是一个字符串
【解决方案2】:

我以这种方式从我的 web api 获取值的原因必须是避免循环引用

services.AddControllers().AddJsonOptions(x =>
            x.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve);

谢谢

【讨论】:

    猜你喜欢
    • 2018-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-15
    • 1970-01-01
    相关资源
    最近更新 更多