I'm having real trouble converting a JSON array to collection of objects in Angular. I've not used Angular for some time, please forgive me if any of my terminology is incorrect.
I have the following products.json file in my project:
[
{
"id": 1,
"name": "Pen",
"description": "The finest blue pen.",
"relatedProducts": [2]
},
{
"id": 2,
"name": "A4 Paper",
"description": "A4 sized printer paper.",
"relatedProducts": [1]
}
]
This product.ts file:
export class Product {
Id: number;
Name: string;
Description: string;
RelatedProducts: Array<number>;
}
My app.component.ts file:
import * as ProductsJson from '../../json-data/products.json';
import { Component, OnInit } from '@angular/core';
import { Product } from 'src/app/models/product';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
productsJson: any = ProductsJson;
products: Array<Product>;
ngOnInit() {
this.products = <Product[]>this.productsJson;
console.log(this.products);
}
}
And finally my app.component.html:
<ul>
<li *ngFor="let p of products">
{{p.Id}} {{p.Name}}
</li>
</ul>
My console log shows the JSON data but it seems as though I'm making some error trying to convert it to a list of Product objects. This is also preventing me from successfully using ngFor in my view as the console error shows, so nothing shows on the page. How can I perform this conversion correctly so the loop works and this data is shown on the view?
