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?
you can use class-transformer which helps you to convert plain javascript objects to real es6 classes. With this real instances you can also use class methods.
import { Component, OnInit } from "@angular/core";
import ProductsJson from "./products.json";
import {plainToClass} from "class-transformer";
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
productsJson: any = ProductsJson;
products: Array<Product>;
constructor() {}
ngOnInit() {
//this.products = <Product[]>this.productsJson;
this.products = plainToClass(Product, this.productsJson as []);
console.log(this.products);
}
}
export class Product {
id: number;
name: string;
description: string;
relatedProducts: Array<number>;
getId(){
return this.id + "_ID";
}
}
template:
<ul>
<li *ngFor="let p of products">
{{p.getId()}} {{p.id}} {{p.name}}
</li>
</ul>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With