I have created a UI where product list is shown and there update button for updating quantity of products(both get and update method will hit my database).Now I have successfully render productlist and my update function is working too. The problem is that view not showing current data after updating my product.Page reload or 2-3 time clicks on update button needed to update my view.try to used spread operator like this this.productList=[...this.productList,res] but is shows error. Here is what i done so far
For fetching Product
productList: any;
ngOnInit(): void {
this.getProduct();
}
getProduct() {
let body = {
filterBy: 'old',
searchKey: '',
};
this._productSs.getProductList(body).subscribe((res: any) => {
res.data.forEach((element: any) => {
Object.assign(element, { count: 0 });
});
this.productList = res;
});
Update Method
updateQuantity(count: any, id: any) {
let body = {
productId: id,
quantity: count.toString(),
};
let productId = id;
let quantity = count.toString();
this._productSs.updateQuantity(quantity, productId).subscribe((res) => {
if (res.message == 'SUCCESS') {
this.getProduct();
}
});
}
html:
<div *ngFor="let item of productList.data;let i=index">
In update method I call getProduct() and get updated product value
CodePudding user response:
The problem may be due to the Object.assign
, since it returns the updated object element after assigning the count, in your case, its updating the value but the returned object is not assigned back to the element.
Try this:
this._productSs.getProductList(body).subscribe((res: any) => {
res.data.forEach((element: any) => {
element = Object.assign(element, { count: 0 });
});
CodePudding user response:
You have to do some refactoring to make it work:
- change productList to an Observable and use async pipe
- use switchMap to avoid subscribe inside another subscribe
here is what you can do
productList$: Observable<any>;
ngOnInit() {
this.productList$ = this.getProduct()
}
getProduct() {
let body = {
filterBy: 'old',
searchKey: '',
};
return this._productSs.getProductList(body)
.pipe(
map((res: any) => {
res.data.forEach((element: any) => {
Object.assign(element, { count: 0 });
});
return res
})
)
}
updateQuantity(count: any, id: any) {
let body = {
productId: id,
quantity: count.toString(),
};
let productId = id;
let quantity = count.toString();
this.productList$ =this._productSs.updateQuantity(quantity, productId).pipe(
switchMap(res => this.getProduct())
)
}
and in your tamplate
<div *ngFor="let item of productList$ | async;let i=index">