Reputation: 55
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 class="container" *ngFor="let item of productList.data;let i=index">
In update method I call getProduct() and get updated product value
Upvotes: 0
Views: 545
Reputation: 21367
You have to do some refactoring to make it work:
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 class="container" *ngFor="let item of productList$ | async;let i=index">
Upvotes: 1
Reputation: 11
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 });
});
Upvotes: 1