后端JS服务代码:
async show(): Promise<any> {
var response: dto = new dto();
var data = await this.sequelize.query('Exec API_Select',
{
type: sequelize.QueryTypes.SELECT
});
if(data.length>0){
data.map((item:any) => {
response.foo1=item.foo1;
response.foo2=item.foo2;
response.foo3=item.foo3;
});
return response;
}
}
前端Angular代码(Service):
getdata(){
const headers = new HttpHeaders().set('Content-Type', 'application/json').set('Authorization','Bearer'+' '+token);
this.http.post<interface1>('http://localhost:3000/getdata/',null,{headers})
.pipe(map(data => ({
foo1:data.foo1,
foo2:data.foo2,
foo3:data.foo3
})))
.subscribe(foo => console.log(foo))
}
现在,如果我在例如data.foo1
中给出假值,那么它就会工作(这意味着Angular中的服务和组件代码是正常的)。后端也工作得很好,因为我可以在邮差中获取数据。唯一的问题是将数据从后端映射到前端。
我试过.subscribe
而不是.map
,但它不起作用。我也试过没有<interface1>
,但结果仍然是一样的。
我是这个领域的初学者,也是Nest JS和Angular的新手。请看一看。谢谢。
编辑:
return this.http.post('http://localhost:3000/getdata/',null,{headers}).subscribe(data => {
this.dataout = data});
如果我将值作为单个变量获取,例如在上面的代码中,data
被获取,并且在后端有一个变量data
。那么它也可以正常工作。唯一的问题是映射。
API响应from Postman:
{
"statusCode": 200,
"isSuccess": true,
"message": "ok",
"data": [
{
"foo1": 3,
"foo2": "abc",
"foo3": "def",
},
{
"foo1": 1,
"foo2": "ghi",
"foo3": "jkl",
}
]
}
使用正确的语法
this.http
.post<interface1>('http://localhost:3000/getdata/',null,{headers})
.pipe(map(({ data }) => ({
foo1:data.foo1,
foo2:data.foo2,
foo3:data.foo3
})))
.subscribe(foo => console.log(foo))
}