Looking for assistance on understanding and implementing the process of adding a product to the cart upon button click. I have a list of products retrieved from an API, each with options to increment quantity using + and - buttons. When the + button is clicked for the first time, I want the product to be added to the cart...
The goal is to trigger a POST request to my API upon clicking the + button, which will then add the selected product to the cart. Additionally, the API call should also verify and update the price if any changes have occurred.
I've created a cart.service file where I've included the following code, however, I keep encountering a 401 error (
{status: 401, message: "token_invalidate"}
message: "token_invalidate"
status: 401
) in the console upon button click... What am I doing wrong here?
cart.service.ts file:
addUpdateProductToCart(quantity: number, produkt: Product) {
return from(Preferences.get({ key: 'TOKEN_KEY' })).pipe(
switchMap(token => {
const headers = new HttpHeaders().set('Authorization', `Bearer ${token.value}`);
// Initialize Params Object
let params = new HttpParams();
// Begin assigning parameters
params = params.append('product', produkt.id);
params = params.append('quantity', quantity);
return this.httpClient.post(`${environment.apiUrl}cart`, { headers, observe: 'response' }, {params});
}),
catchError(err => {
console.log(err.status);
if (err.status === 400) {
console.log(err.error.message);
}
if (err.status === 401) {
// this.authService.logout();
// this.router.navigateByUrl('/login', { replaceUrl: true });
}
return EMPTY;
}),
);
};
And here's how I'm triggering the POST request on the page containing the product listings (subcategory.page.ts):
incrementQty(index: number, produkt: Product) {
const newQty = this.products[index].step += 1.00;
this.cartService.addUpdateProductToCart(newQty, produkt).subscribe(
data => {
console.log(data);
},
error => {
console.log('Error', error);
}
);
}
HTML Code:
<ion-label>
<div class="d-flex ion-justify-content-between">
<div class="prod-details-wrapper">
<p class="product-id">{{ produkt.product_code }}</p>
<p class="product-em">EM: {{ produkt.unit }}</p>
<p class="product-packaging">Pakiranje: {{ produkt.min_weight }} {{ produkt.unit }}</p>
</div>
<div class="qty-input-wrapper">
<ion-item lines="none" slot="end">
<ion-icon color="vigros" name="remove-circle" (click)="decrementQty(i, produkt)"></ion-icon>
<ion-input type="number" value="0" min="0" step="1" [(ngModel)]="produkt.step"></ion-input>
<ion-icon color="vigros" name="add-circle" (click)="incrementQty(i, produkt)"></ion-icon>
</ion-item>
</div>
</div>
</ion-label>