I need help with understanding and implementing how to add a product to my cart when clicking a button. In my example I have a list of products that I get from an API and each product has a + and - button to increase its quantity and on first click on + button to add it to cart...
I want to achieve that on the click of + button a post request happens to my API that then adds this product to my cart. My API call also check and updates the price if there has been a price change.
Now I have created a cart.service file where I added the bellow code but I keep getting a 401 error (
{status: 401, message: "token_invalidate"}
message: "token_invalidate"
status: 401
) in console on button click... What is my mistake 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 this is how I'm triggering this POST request in the page where the products are listed (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);
}
);
}
And the 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>
this.httpClient.post(url, body, options)
. If there is no body to pass, then pass null
. Take a look to the official documentation. return this.httpClient.post(environment.apiUrl + 'cart', { headers, observe: 'response' }, {params});
to return this.httpClient.post(environment.apiUrl + 'cart', null, { headers, observe: 'response', params });
. Your template string ${environment.apiUrl}cart
is perfectly fine, i just changed it for formatting purposes. append
the params and not to reassign them like this: // Begin assigning parameters params.append('product', produkt.id); params.append('quantity', quantity);
and check the request url in the browser devtool. Post needs a body doesn't matter if its empty or not.
if you use Visual Code you can hover over Methods to see what parameters are necessary and in what order. ! or ? after a Parameter doesnt mean you can just skip it just put it down as null or undefined.
-> post(url, body, headers, params)
The way you add your token should work. Are you 100% sure you have a valid token?
If not put console.log(token) after you receive it and try the request with postman/swagger and see if you still get a 401 error.
Also if its your API just debug it and find out at what point the Authorization fails.