I am trying to access a returned observable, but I get the error that the value does not exist. I want to access the property of the interface
Below are the code
Interface class
export interface ListModelServer {
id: Number;
name: String;
category: String;
description: String;
image: String;
price: Number;
quantity: Number;
images: String;
}
export interface ListModelServerResponse {
stores: any;
count: number;
list: ListModelServer[];
}
Here is the service class
//get all products
getAllProducts(storeId: Number): Observable<ListModelServer[]> {
return this.http.get<ListModelServerResponse>(this.url 'list/' storeId)
.pipe(map(response => response.stores
));;
}
In the component, I want to use the fields defined in the interface
export class FoodListComponent implements OnInit {
list: ListModelServer[];
@ViewChild('quantity') quantityInput!: any;
constructor(private listService: ListService, private router: Router, private route: ActivatedRoute,
private cartService: CartService
) {
}
ngOnInit(): void {
//fetch all prod for a particular store
this.listService.getAllProducts(this.storeId).subscribe(food => {
this.list = food;
console.log(this.list);
});
}
Increase() {
let value = parseInt(this.quantityInput.nativeElement.value);
value ;
if (this.list.quantity >= 1){
value ;
if (value > this.list.quantity) {
// @ts-ignore
value = this.list.quantity;
}
} else {
return;
}
this.quantityInput.nativeElement.value = value.toString();
}
Decrease() {
let value = parseInt(this.quantityInput.nativeElement.value);
value--;
/* if (this.list.quantity > 0){
value--;
if (value <= 0) {
// @ts-ignore
value = 0;
}
} else {
return;
} */
this.quantityInput.nativeElement.value = value.toString();
}
}
The error comes from increse() and decrease() methods.
this.list.quantity
How do I properly access the properties of an interface in another class??
CodePudding user response:
Since you are working on the list of objects that contains the quantity you have to define on which element you want to increase/decrease the quantity. Check the code below:
Increase(indexOfElementQuantity: number) {
let value = parseInt(this.quantityInput.nativeElement.value);
value ;
if (this.list[indexOfElementQuantity].quantity >= 1){
value ;
if (value > this.list[indexOfElementQuantity].quantity) {
// @ts-ignore
value = this.list[indexOfElementQuantity].quantity;
}
} else {
return;
}
this.quantityInput.nativeElement.value = value.toString();
}
of course, you can also pass the id of the particular object as well
Increase(listModelId: number) {
let value = parseInt(this.quantityInput.nativeElement.value);
let listModel = this.list.find(x => x.id === listModelId)[0];
value ;
if (listModel.quantity >= 1){
value ;
if (value > listModel.quantity) {
// @ts-ignore
value = listModel.quantity;
}
} else {
return;
}
this.quantityInput.nativeElement.value = value.toString();
}