Search code examples
angularangular-httpclient

Angular HttpClient get method returns object with wrongly named attributes


I have a web controller with a GET method Products. This method returns Enumerable of type Product.

        public class Product
        {
            public float Price;
            public string Name;
            public string ImageURL;
            public int Quantity;

            public Product()
            {
                this.Quantity = 1;
            }
        }

I have created an Angular component which reads data provided by the controller method as follows:

constructor(http: HttpClient, @Inject('BASE_URL') baseUrl: string) {
    this.grandTotal = 0;
    this.httpClient = http;
    this.url = baseUrl;
    http.get<Product[]>(baseUrl + 'api/SampleData/Products').subscribe(result => {
      this.products = result;
      this.slicedProducts = new Array<Product[]>();
      for (let i = 0; i < this.products.length / 3; i++) {
        this.slicedProducts[i] = this.products.slice(i * 3, i * 3 + 3);
      }

    }, error => console.error(error));
  }

My problem is that property names in the objects at Angular side are incorrectly named, e.g.: Product.Quantity is Product.quantity, so when I try to use these properties later on in my functions, I have an error that Quantity does not exist. When I use quantity, the code works.


Solution

  • If you are using Java. Check your settings for the object conversion from Java object to Json object. Assuming you are using Spring Boot on the backend, you may need to configure your Jackson to keep the field names as is. I assume the fields are converted to Camel case by default.