I have a TypeScript model that looks like this:
export class Product {
id:number;
name:string;
brand:Brand;
price:number;
shippingPrice:number;
description:string;
photoName:string;
productType:ProductType;
purchaseCounter:number;
rating:number;
volume:string;
ingredients:string;
}
and a json file that populates this model:
{
"id": 1,
"name": "xxx",
"description": "xxx",
"price": 12.34,
"purchaseCounter": 12,
"photoName": "xx",
"shippingPrice": 12.99,
"volume": "xxx",
"rating": 4.7,
"ingredients": "A,B,C",
"brand": {
"id": 1,
"name": "xx"
},
"productType": {
"id": 3,
"name": "xxx"
}
}
Now in my TypeScript component, I have a function like this :
public getIngredients():String [] {
return this.product.ingredients.split(",");
}
Every time I invoke this function, I encounter an error:
"TypeError: Cannot read property 'split' of undefined"
However, when I change the body of the function to something like this:
public getIngredients():String [] {
if (this.product.ingredients == null) {
return null;
}
return this.product.ingredients.split(",");
}
everything works fine and the split function works properly. Do you have any idea why checking if ingredients is not null fixes it? I must admit that I am just starting my adventure with JavaScript and TypeScript. Thanks!
UPDATE: I instantiate the Product variable here:
export class ProductOverviewComponent implements OnInit {
private product:Product;
private errorMessage:string;
constructor(private productService:ProductService) {
this.product = new Product();
}
ngOnInit():void {
this.productService.getProduct()
.subscribe(
product => this.product = product,
error => this.errorMessage = <any>error);
}
}
For now, I fetch data from the JSON file but in the future, I will fetch it from the server. Another thing is that I pass the product to another component using @Input().
This is how I call the getIngredients function:
<div class="col-md-12">
<div class="property-text">
<ul>
<li *ngFor="let ingredient of getIngredients()">
{{ ingredient }}
</li>
</ul>
</div>
</div>