【发布时间】:2020-08-31 15:00:03
【问题描述】:
我在 webapi 中有一个类
public class Respuesta
{
public int Exito { get; set; }
public string Mensaje { get; set; }
public object Data { get; set; }
}
并在 ASP.NetCore 中有如下方法:
public IActionResult Get()
{ ..
using (NegociosAPIContext db = new NegociosAPIContext())
{
var lst = db.Cliente.ToList();
oRespuesta.Exito = 1;
oRespuesta.Data = lst;
return Ok(oRespuesta);
}
在另一边 (appAngular),我在 module.ts 中进行了导入
import {HttpClientModule } from '@angular/common/http';
这是我的代码服务:
图片
在我的控制器上
import { Component, OnInit } from '@angular/core';
import {ApiclienteService} from '../service/apicliente.service';
@Component({
selector: 'app-cliente',
...
})
export class ClienteComponent implements OnInit {
constructor(private apiCliente: ApiclienteService) {
apiCliente.getClientes().subscribe(response => {
console.log('respuesta:'+response);
})
}
…
}
如果我在浏览器中调用 api,我会得到这个
{
"exito":1,
"mensaje":" ",
"data":[
{
"id":1,
"nombre":"Liliana Torres"
},
{
"id":2,
"nombre":"Redmon Redinton"
}
]
}
然后在 Angular 应用程序中,我只得到 {object Object}。当我尝试输入 console.log('respuesta:'+response.json); 这会抛出
undefined
我忘记了一个重要的事情是打字稿中的 mi 类;我有:
import { Icliente } from './ICliente';
export interface Response {
exito:number;
mensaje:string;
data:Icliente[];
}
【问题讨论】:
-
代替
console.log('respuesta:'+response);你可以试试:`console.log('respuesta:', response);` -
你应该得到
data:{"exito":1,"mensaje":null,"data":[{"id":1,"nombre":"Redmon Redinton"}]}。我认为:在第一个数据之后丢失,}在最后丢失。 -
@Sébastien Temprado 我将我的字符串更新为:{"exito":1,"mensaje":" ","data":[{"id":1,"nombre":"Liliana Torres "},{"id":2,"nombre":"Redmon Redinton"}]} 我在 JSON Validator 中测试它没问题,但我无法获得 mi [数据]
标签: javascript json angular typescript asp.net-core