I am pretty new with Angular and I stuck with problem building up my portfolio project. The problem is with receiving list of (nested) objects like this:
"$id": "1",
"data": {
"$id": "2",
"$values": [
{
"$id": "3",
"id": 1,
"name": "producto",
"shortDescription": "prod11111",
"longDescription": "lorem ipsum bla bla",
"category": "1",
"price": 50.00,
"stockLevel": 10,
"orderDetails": {
"$id": "4",
"$values": []
}
},
{
"$id": "5",
"id": 2,
"name": "segundo",
"shortDescription": "prod222",
"longDescription": "lorem ipsum",
"category": "2",
"price": 30.00,
"stockLevel": 20,
"orderDetails": {
"$id": "6",
"$values": []
}
}
]
},
"error": null
}
This is my app.component.ts:
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
title = 'Shop';
products: any[] = [];
constructor(private http: HttpClient) {}
ngOnInit(): void {
this.http.get('https://localhost:5001/api/products').subscribe((response: any) => {
this.products = response.data;
}, error => {
console.log(error);
});
}
}
This is app.component.html:
<app-nav-bar></app-nav-bar>
<div class="container" style="margin-top: 140px;">
<h1>Welcome to {{title}}!</h1>
<ul>
<li class="list-unstyled" *ngFor="let product of products">
{{product.name}}
</li>
</ul>
</div>
I looked thru StackOverflow for similar problems but cannot resolve this in my case. I think that there is problem because of arrays of arrays or nested objects.
Any help is appreciated!
response.datais not an array. I think you wantresponse.data.$values. so dothis.products = response.data.$values;