3

I have an application with Angular 2.x written in typescript where I need to create a JSON Structure dynamically based on User Interactions with the UI. The JSON Structure consists of key:value parameters and arrays. This JSON Structure is then sent to an API as HTTP Parameter.

A simplified example for the JSON structure:

{
  'key_1': 'param_1',
  'key_2:  'param_2',
  'array_key_1': [
     {
       'key_1_1': 'value_1_1',
       'key_1_2': 'value_1_2
     },
     {
       'key_2_1': 'value_2_1',
       'key_2_2': 'value_2_2'
     }
  ],
  'array_key_2': [
           {
       'key_1_1': 'value_1_1',
       'key_1_2': 'value_1_2,
       'someArray': [...]
     },
     {
       'key_2_1': 'value_2_1',
       'key_2_2': 'value_2_2'
       'someArray': [..]
     }
  ]
}

This JSON Structure is used as a query for a Database.

Current Implementation

Initially I declare a public sqlJSON: Object = {} in the component and use ngOnInit() LifeCycleHook to initialize the empty arrays (this is needed because if not initialized, Angular will not recognize the array when an entry is pushed into it).

I use the ngOnChanges LifeCycleHook to reset the JSON Structure if the user changes the to another topic of interest. For instance, sqlJSON['array_key_1] = [] and so on.

Query

Is there a better way to use create such JSON Structures? For instance can one use localStorage for the same keeping in mind that the JSON might turn out to be very large if the user interacts with the UI alot? Also are there any memory constraints while storing such JSON Structures in localStorage.

It is also worth informing that since the Backend Requirements keep changing, the above mentioned JSON Structure needs to keep adding/removing new key:value parameters.

Can an interface be used for the building this JSON? I think since parameters keep added/removed an interface would be more adaptable.

Shan-Desai
  • 3,101
  • 3
  • 46
  • 89
  • Hi, I'd subscribe to Router events change as it's already there and less error prone. Please read this thread: https://stackoverflow.com/questions/35912932/angular-2-router-event-listener https://angular.io/guide/router – t3__rry Mar 05 '18 at 10:56
  • Hi, my query is not whether there is a route change within my application. To clarify, the user interacts within the same route of the component and within the component there is _dynamic JSON_ that gets changed with every interaction. Hence your link does not answer my question – Shan-Desai Mar 05 '18 at 11:04
  • Ok yes it doesn't help. For storing 'larger' amount of data instead of `localStorage` you can use `IndexedDb`. This way you can store datas on interaction and query it when you need to. – t3__rry Mar 05 '18 at 11:12

0 Answers0