简体   繁体   中英

Angular 9 Best Practice to handle array with different objects in a Http Request

I'm very new to Angular and also to web development, so if I may use terms not precisely or if I explain my problem a little weird, please forgive;-)
To the problem:
I work with Angular 9 and am making a http request (get and post) to an API via the HttpModule. The response object (as well as the post object) is a JSON object which amongst other objects includes an array with variable objects:

inputs: [
    {
      id: string,
      sT: string,
      stl: string,
      mCC: number
    },
    {
     id: string,      
     sT: string,
     val: string,
     dT: string
    }

  ]

What I read so far is, that you usually create an interface for the response object, so you can access the objects properties with the name of the property. I did this for all other properties, also for nested ones, but with the array above I have the problem, that the objects are not having the same attributes. What I did is to create an interface for 'Input' with optional attrubutes, like this:

// Single interface with optional attributes

export interface Input {
  id: string;
  sT: string;
  dT?: string;
  val?: string;
  mCC?: number;
  stl?: string;
}

But I feel, that this is not the way of how you are usually typing this sort of object. How do you do this the 'Angularish way'? Or is this more a TS question?

I would be glad to find a best practice for this sort, as I guess I will see this type of object often in the future.

If you have not idea what kind of attributes will be return you can declare something like that

interface Input{
  [key: string]: any;
}

If you know some of the elements will be always here, you can be more precise

interface Input{
  id: string;
  sT: string;
  [key: string]: string|number;
}

If you know you have a limited random list of elements, as the six of your sample, your solution is ok.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM