Reputation: 2803
My json looks as follows:
{
"content": [
{
"id": 1,
"name": "test name",
"email": "[email protected]",
"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
}
and I want to populate with it my angular 8
website.
In my api.service.ts
I have:
getMyStructure(): Observable<HttpResponse<MyStructure[]>> {
return this.http.get<MyStructure[]>(
localUrl, { observe: 'response' });
}
and in app.components.ts
I have:
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
Now, myStructure
is an interface, that contains:
export interface Shelter {
id: number;
name: string;
email: string;
img_url: string;
field1: string[];
field2: string[];
creationDateTime: string;
}
but the data inside myStructure
somehow is not populated. I have no idea why, can you help me with that?
Upvotes: 0
Views: 101
Reputation: 6529
Your API doesn't return MyStructure[]
it returns:
Please chose a better name for the interface
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;
});
}
Take note of the arrow function in the subscribe
.subscribe((resp) => {
Upvotes: 1
Reputation: 222692
You need to add the console.log inside the subscribe
part of the code, otherwise as it gets executed first, you will see it as 0. Change it as,
.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);
});
EDIT:
As I see you want to display the content array on the front end, so you need to assign the data as,
this.myStructure = resp.body.content;
Upvotes: 2