[英]The data from json is not populated in my angular 8 app
我的 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
是一个接口,它包含:
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;
您的 API 不返回MyStructure[]
它返回:
请为接口选择一个更好的名称
interface SomeStructure {
content: MyStructure[];
page: number;
size: number;
totalElements: number;
totalPages: number;
last: boolean
}
api.service.ts
getMyStructure(): Observable<HttpResponse<SomeStructure>> {
return this.http.get<SomeStructure>(
localUrl, { observe: 'response' });
}
app.component.ts
myStructure: MyStructure[] = [];
getMyStructure() {
this.api.getMyStructure()
.subscribe((resp) => {
this.myStructure = resp.body.content;
});
}
注意 subscribe 中的箭头函数
.subscribe((resp) => {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.