gpt4 book ai didi

javascript - 来自 json 的数据未填充在我的 Angular 8 应用程序中

转载 作者:行者123 更新时间:2023-11-28 16:53:06 25 4
gpt4 key购买 nike

我的 json 如下所示:

    {
"content": [
{
"id": 1,
"name": "test name",
"email": "test@test.com",
"img_url": "url",
"field1": [
{
"id": 10,
"userId": 1,
"registeredAt": "2020-01-09T22:21:23.272",
"amount": 200
}
],
"field2": [
{
"id": 11,
"userId": 1,
"registeredAt": "2020-01-09T22:21:46.113",
"amount": 200
}
],
"creationDateTime": "2020-01-05T00:00:00Z"
}
],
"page": 0,
"size": 30,
"totalElements": 1,
"totalPages": 1,
"last": true
}

我想用它填充我的 angular 8 网站。

在我的 api.service.ts 中,我有:

getMyStructure(): Observable<HttpResponse<MyStructure[]>> { 
return this.http.get<MyStructure[]>(
localUrl, { observe: 'response' });
}

app.components.ts中我有:

myStructure: MyStructure[] = []; 

getMyStructure() {
this.api.getMyStructure()
.subscribe(function(resp) {
console.log(resp.body.length); //this prints undefined
console.log(resp.body) // this prints {content: Array, page: 0, size: 30, totalElements: 1, totalPages: 1, …}
this.myStructure = resp.body;
});
console.log("after");
console.log(this.myStructure.length); //this prints 0

现在,myStructure 是一个接口(interface),其中包含:

export interface Shelter {
id: number;
name: string;
email: string;
img_url: string;
field1: string[];
field2: string[];
creationDateTime: string;
}

myStructure 内的数据不知何故未填充。我不知道为什么,你能帮我吗?

最佳答案

您需要在代码的subscribe部分添加console.log,否则当它首先执行时,您将看到它为0。将其更改为,

.subscribe(function(resp) { 
console.log(resp.body.length); //this prints undefined
console.log(resp.body) // this prints {content: Array, page: 0, size: 30, totalElements: 1, totalPages: 1, …}
this.myStructure = resp.body;
console.log("after");
console.log(this.myStructure.length);
});

编辑:

据我所知,您想在前端显示内容数组,因此您需要将数据分配为,

 this.myStructure = resp.body.content;

关于javascript - 来自 json 的数据未填充在我的 Angular 8 应用程序中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59695218/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com