Skip to content
Advertisement

Retrieve a list of cart items by passing in a user

A typical shopping cart problem. The CartItem class is being injected with a User class and Product class. I already have a user, and I need to pass in the user to return a list of cart items. But the front end failed to receive it. The browser console returned 400, and Postman returned 405 for the back end.

In the back end the Spring Boot entity classes, getters and setters and constructors are not shown here.

This is the CartItem class:

@Entity
@Table(name = "cartItems")
public class CartItem {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;

@ManyToOne
@JoinColumn(name = "pId")
private Product product;

@ManyToOne
@JoinColumn(name = "uId")
private User user;

private int quantity;

This is the Product class:

@Entity
@Table(name = "products")
public class Product {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private Integer price;

This is the User class:

@Entity
@Table(name = "users")
public class User {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String firstName;
private String lastName;

This is the customized repository method:

List<CartItem> getByUser(User user);

This is the service method:

public List<CartItem> getCartItemsByUser(User user) {
    return repo.getByUser(user);
}

The is the controller method:

@GetMapping("/cart/get-items")
public List<CartItem> getCartItemByUser(@RequestBody User user) {
    return service.getCartItemsByUser(user);    
}

For the front end I’m using Angular, here is the service method:

getCartItemsByUser(user: User) {
return this.http.get<CartItem[]>(`${this.baseUrl}/cart/get-items`);
}

This is the ngOnInit() method:

this.cartItemService.getCartItemsByUser(this.user).subscribe({
  next:(res) => this.cartItems = res
})

This is the ng CartItem class:

export class CartItem {

cId!: number;
user: User;
product: Product;
quantity: number = 1;


constructor(user: User,product: Product) {
    this.user = user;
    this.product = product;
}

I’m sure there are some fatal flaws in the code. It’d be great if someone can point it out.

Advertisement

Answer

The main problem is that you are not doing anything with the User object during the network call:

getCartItemsByUser(user: User) {
    return this.http.get<CartItem[]>(`${this.baseUrl}/cart/get-items`);
}

Angular does not support the passing body in request params, I would suggest you pass in the user id in the URL, like:

getCartItemsByUser(user: User) {
    return this.http.get<CartItem[]>(`${this.baseUrl}/cart/get-items/${user.id}`);
}

and expect the same in the backend as URL param. Now in the backend, you can extract the user by id and do whatever computation you want.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement