I have an endpoint that returns this Json:
{
"result": [
{
"id": 1,
"name": "Kayak",
"category": "Watersports",
"description": "A boat for one person",
"price": 27500,
"currencyCode": "EUR"
},
{
"id": 2,
"name": "Lifejacket",
"category": "Watersports",
"description": "Protective and fashionable",
"price": 48095,
"currencyCode": "EUR"
},
{
"id": 3,
"name": "Soccer Ball",
"category": "Soccer",
"description": "FIFA-approved size and weight",
"price": 1950,
"currencyCode": "EUR"
}
]
}
I have a class called Product
in Angular:
import { Money, Currencies } from 'ts-money';
export class Product {
private money: Money;
public Amount = this.money.amount;
public constructor(
public Id: number,
public Name: string,
public Category: string,
public Price: number,
public Description: string,
public CurrencyCode: string) {
this.money = new Money(Price, CurrencyCode);
}
public GetPrice(): Money {
return this.money;
}
}
I made this code in Angular:
export class ProductComponent implements OnInit {
constructor(private datasource: ProductDataSource) {
}
private products: Product[];
ngOnInit(): void {
this.datasource.GetProducts()
.subscribe((data) => {
this.products = data;
});
}
}
}
This code successfully returns an array of JSON objects that have the same properties as Product
. Now, when I subscribe to this observable:
this.datasource.GetProducts()
.subscribe((data) => {
// this.products is a class property of type Product[]
this.products = data; // How do I make this work?
});
I can not figure out how to make the transition from JSON object to Angular class. My HTML page does not recognize this.products
as an array of Product
objects. What do I do?