What steps can I take to ensure that my JSON structure aligns perfectly with my interface?

When I receive the json response from my product information api, it is structured like this:

{
    _productDepartment : null,
    _productClass : null,
    _productMaterial : null,
    _productStyle : null,
    _productDetails :
    {
        _productSkuKey : 800,
        _description : "Product Description",
        _collection : "Collection1",
        _department : 200,
        _productSize : "Size1",
        _productClass : 45,
        _productStyle : 1234,
        _material : "Product Material",
        _price : 100.00,
        _mediaFileName : "XYZ"
    },
    _products : null,
    _errorDetails :
    {
        _message : "success",
        _status : 200
    }
}

For this specific api call, my main focus lies on extracting the productDetails and errorStatus. To structure the productDetails object based on the json response received above, I have created two interfaces: one for product and the other for productdetails.

This is how my interfaces look:

//product.ts
import { IProductDetails } from './productDetails';

export interface IProduct {

    productDepartment: string;
    productClass: string;
    productMaterial: string;
    productStyle: string;
    productDetails: IProductDetails;
    products: null;
    errorDetails: string;

}

//productDetails.ts
export interface IProductDetails {
    productSkuKey: number;
    description: string;
    collection: string;
    department: number;
    productSize: string;
    productClass: string;
    productStyle: number;
    material: string;
    price: string;
    mediaFileName: string;
}

In one of the services, I make this call:

getProducts(storeId: string, productSKU: string) {
    this.products = this.baseUrl + '/products/' + storeId + '/' + productSKU;
    return this.http.get<IProduct[]>(this.products).catch(this.errorHandler);
  }

And in one of the components, I use the service like so:

this._transactionService.getProduct('98', '343').subscribe(data => this.products = data._productDetails);

My query is whether this approach ensures that the object used in my code aligns with the json response data. How does it understand to map _productSkuKey with productSkuKey in my interface?

Answer №1

It is crucial that the structure of your interface aligns perfectly with the structure of your JSON data, ensuring that all properties have identical names.

To achieve this alignment, you may need to adjust the interfaces by adding or removing underscores to match those in the service.

Keep in mind that while defining an interface sets expectations for TypeScript, it does not guarantee that the incoming JSON will match. Type information is lost after compilation, leaving room for variations in data received.

Answer №2

If for any reason you prefer not to change interface props with underscores, you can utilize a Class instead of Interface, like so:

export class SomeClass {
  productDepartment = 0;
  productClass = 0;

  constructor(data: any) {
    for (let prop of Object.keys(data)) {

      if (this.hasOwnProperty(prop)) {
        this[prop] = data[prop];
      } else {
        let gProp = prop.substring(1);
        if (this.hasOwnProperty(gProp)) {
          this[gProp] = data[prop];
        }
      }
    }
  }
}
...
 this.data = new SomeClass({
  _productDepartment: 12,
  _productClass: 34
});

This will yield the following result:

SomeClass {productDepartment: 12, productClass: 34}

VIEW CODE EXAMPLE

Within your service logic:

getProducts(storeId: string, productSKU: string) {
    this.products = this.baseUrl + '/products/' + storeId + '/' + productSKU;
    return this.http.get<Product[]>(this.products)
     .map(prodRes => prodRes.map(prod => new Product(prod)))
     .catch(this.errorHandler);
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for organizing JSON Objects in TypeScript

I'm looking to sort a JSON object within my Angular application. The JSON object I'm working with appears as follows: {"9 - ABCDEF":{"isSucceeded":true}, "18 - Remote Software Update":{"isSucceeded":true,}, "4 - n.a."{"isSucceeded":true,}} My ...

React and MaterialUI Chrome Extension - Data did not populate in the table

Currently, I am in the process of developing a browser extension. My main challenge lies in displaying data within a table that has been created using MaterialUI and React. Despite not encountering any errors, everything else renders perfectly. The console ...

Top Tips for Layering Components in Angular 5

Just starting out with Angular, currently in the process of creating a sample website. Created a cover page component named <app-coverpage> and have additional components that I want to overlap the cover page as part of the background effect. All c ...

When running scripts, Protractor is unable to perform a click action in Safari, even though it works perfectly in

Currently, I am in the process of developing an angular application and utilizing directconnect for Chrome and Firefox. All my test scripts are functioning as expected, however, a new requirement has been introduced to run these same tests on Safari. To ...

Unable to retrieve the key value from a child object in Angular 2 when working with JSON Data

Currently, I am using Angular and attempting to extract data from the child object's key value. Here is the JSON data provided: "other_lessons": [ { "id": 290, "name": "Christmas Test #290", "course": { "id": ...

Tips for transmitting static information from route configuration to components

I am facing an issue with passing static data from a route to a component in Angular. Despite trying to pass the data in the route configuration, I keep receiving empty data when subscribing to it from the ActivatedRoute. Below is the code snippet that I h ...

Choose a Spot on the Open Layers map using a marker or icon

As a beginner in the world of Open Layers, I'm eager to learn how to utilize markers or icons to obtain user location. Additionally, I hope to harness the power of Angular to extract these location details. ...

Intercept Axios Responses - Retrieving API Responses for HTTP Statuses that are not in the 200 range

I've set up a custom Axios instance with interceptors for handling responses. As per the Axios documentation, the success interceptor is triggered for 2xx statuses while the error interceptor handles any other status codes. My goal is to show an error ...

Experiencing a problem with Typescript validation while integrating Storybook with Material-UI (

Encountering a Typescript validation issue while attempting to pass args as children to a Material-UI button in Storybook :-/ Any suggestions on how to resolve this and avoid the Typescript error? I suspect it is caused by not passing a ReactNode. Thanks ...

Cordova's FileReader takes precedence over TypeScript's FileReader functionality

I encountered an issue when adding the cordova-plugin-file-transfer plugin, where I received the error message: reader.addEventListener is not a function. This problem arises due to Cordova FileReader class overriding typescript FileReader. How can this ...

Sending data between Angular 4 components without using parent-child relationships

Current Scenario: In my project, there is a component that displays tiles, with each tile representing an item from an array. These items are looped over using ngFor. The requirement is that when a tile is clicked, the corresponding object should be passe ...

Ionic 2: Inconsistency detected in the expression after it was verified

After going through this response, this solution and this advice (as well as numerous others), I still find myself struggling to comprehend how to resolve this issue in my current approach. The task at hand involves creating an event countdown timer that ...

Developing a constrained variable limited to specific values

Recently delving into Typescript - I am interested in creating a variable type that is restricted to specific values. For instance, I have an element where I want to adjust the width based on a "zoom" variable. I would like to define a variable type call ...

The debate between TypeScript default generic types and contextual typing

Contextual Typing in TypeScript is an interesting feature where the correct type is inferred from the return value when a generic type is not specified. While it usually works well, there are instances where it can be unpredictable. For example, in some c ...

The DHTMLX Gantt tool is throwing an error message saying "TS6137: Type declaration files cannot be

Lately, I've noticed some issues with my code that were not present before. It seems like something may have changed in either typescript or dhtmlxgantt. Whenever I compile the code, I keep running into these errors: Error TS2306: File 'project ...

The "unsubscribe" property of undefined cannot be read (rxJS - Subscription)

Exploring the world of subscriptions and observables in rxJS is my current focus. My goal is to modify the interval for an Observable by unsubscribing and then resubscribing with the updated interval. While this seems like a straightforward task, I could ...

The ngOnChanges() function fails to detect changes in the boolean @Input value coming from the parent component

Whenever I try to pass a dropdown toggle value to a child component, it works fine when the toggle is true but not when it's false. Despite using ngOnChanges to detect changes, it only picks up on the true values. ChildComponent export class ChildCom ...

Guide on how to "attach" the routes of an Angular 2 module to a specific location within the routing structure

Let's consider a scenario where the main routing module is defined as follows: // app-routing.module.ts const appRoutes: Routes = [ { path: 'login', component: LoginComponent }, { path: 'auth', ...

Perform an Angular HTTP request and await responses from multiple sources

I'm currently working with Angular 11 and looking to make an HTTP call to an API that will trigger a server-side process. Here's the code for the HTTP call: processData(data) { return this.httpClient.post('https://myurl/api/process&apos ...

Extracting Information from a Table in Angular 7

Hi there, I'm new to this forum so if I break any rules, please let me know! I'm working with the code below in my app.component.html: <tr *ngFor="let item of items" (click)="getClient($event)"> <td> {{ item.nr }} </td> ...