my problem is the following, I have a product variable that saves a json which I can display in the html without any problem, but what I want is to add the price to the total and I get undefined
import { Component, OnInit } from '@angular/core';
import { ProductoService } from '../../services/producto.service'
@Component({
selector: 'app-caja',
templateUrl: './caja.component.html',
styleUrls: ['./caja.component.css']
})
export class CajaComponent implements OnInit {
public total:number=0;
public producto:any;
public idProducto:number;
constructor(protected productoServices: ProductoService) { }
ngOnInit() {
}
lanzar(id:number){
this.buscarProducto(id);
this.total += this.producto.precio;
}
buscarProducto(id:number){
this.productoServices.getProducto(id).subscribe(data=>(this.producto = data));
}
}
ERROR TypeError: "this.product is undefined"
You are getting the json asynchronously, so you cannot ensure that it has a value at the time you are calculating the total.
The logical thing would be to calculate the total within the
callback
:You would even have the function left over
lanzar(id)
. However, calculating the total like this can only cause problems. It is best to store the prices in aarray
and calculate the total where necessary.But if that's what I suspect you want to do, you might want to think about saving the products as an
array
in case you need to remove or add any later. The total is very simple to obtain as a property:edited
Since it is not very safe to work with the type
any
, we can declare an interface with the minimum attributes that our product would have: