What is the best way to transfer information from a service to JSON format?

Currently, I am developing an Angular 6 application that involves creating a dynamic form using data obtained from a JSON file.

JSON Data:

  jsonData: any = [
    {
      "elementType": "textbox",
      "class": "col-12 col-md-4 col-sm-12",
      "key": "project_name",
      "label": "Project Name",
      "type": "text",
      "value": "",
      "required": false,
      "minlength": 3,
      "maxlength": 20,
      "order": 1
    },
    {
      "elementType": "textbox",
      "class": "col-12 col-md-4 col-sm-12",
      "key": "project_desc",
      "label": "Project Description",
      "type": "text",
      "value": "",
      "required": true,
      "order": 2
    },
    {
      "elementType": "dropdown",
      "key": 'project',
      "label": 'Project Rating',
      "options": [
        { "key": 'average', "value": 'Average' },
        { "key": 'good', "value": 'Good' },
        { "key": 'great', "value": 'Great' }
      ],
      "order": 3
    }
  ];

In the dropdown section above, I aim to retrieve the options array from a service call by making it dynamic instead of hardcoding as it is currently shown.

The service function in dynamic-form.component.ts:

  getDropdownValues(url, token) {
    this.service.get(url, token).subscribe(res => {
      console.log(res.data);
    });
  }

The response from res.data consists of:

  {
    data: [
        { "key": 'average', "value": 'Average' },
        { "key": 'good', "value": 'Good' },
        { "key": 'great', "value": 'Great' }
    ]
  }

This array will serve as the options for the dropdown in the JSON data structure.

Though the JSON is currently included in the .ts file, it will eventually be moved to a separate .json file.

For a demonstration, check out the working stackblitz: https://stackblitz.com/edit/angular-x4a5b6-ng8m4z

I would appreciate guidance on integrating the data fetched from the service (res.data) into the dropdown options within the JSON.

Answer №1

It is important to consider the data you are receiving and the data you actually need. For example, you can:

getOptions():Observable<any[]>
{
   //of, create an observable
   return of(
     [{key:"option1",data:["option1_1","option_1_2"]},
      {key:"option2",data:["option2_1","option_2_2","option_2_3]},..
     ])
}

getModel():Observable<any[]>
{ 
  return of(
            [{key:"option1",...},
             {key:"option2",..}
     ])
}

Using switchMap to receive the full model ensures that you do not double subscribe to the same call.

getFullMode():Observable<any[]>
{
     return getOptions().pipe(switchMap(
        opts=>{
           return getModel().pipe(map(mod=>{
             //..here transform "mod" using the values of opts
             //e.g.
             let option=opts.find(p=>p.key=mod.key);
             mod.options=option.data
           }))
        })
     )
}

If dealing with a simple case with fixed JSON data for a dropdown element, you can simply modify the data directly.

getFullJson(url,token) 
{
    this.service.get(url,token).pipe(map(opt=>{
      //we don't want return opt, instead transform the jsonData.
      let element=this.jsonData.find(e=>e.elementType=='dropdown');
      if (element)
         element.option=res.data
      return this.jsonData
    }))
  }).subscribe(res=>console.log(res));

If your JSON data comes from an observable source, use switchMap instead of map to wait for the outer call to complete before processing the inner one.

getFullJson(url,token) {
    this.service.get(url,token).pipe(switchMap(opt=>{
    //we don't want return opt, instead transform the jsonData
    //use pipe(map) to transform data
      return this.service.getJsonData(pipe(map(jsonData=>{
         let element=jsonData.find(e=>e.elementType=='dropdown');
         if (element)
           element.option=res.data
      return this.jsonData
    }))
  }).subscribe(res=>console.log(res));

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

Retrieving the content of input elements within a div post removal

I have a situation where I need to dynamically add input text fields inside a div and then delete the div while retaining the values of the input field in a variable. Here's an example code snippet that demonstrates this: $(document).ready(funct ...

Searching within an array in MongoDB can be easily accomplished using the

I have encountered a challenge with my mongodb JSON array as I am struggling to locate specific categories, for example: { name:"hoyts"} I have attempted various queries like {categories.name:"hoyts"} but unfortunately, none of them have yielded the desi ...

Tips for displaying content from JavaScript onto a div element in HTML

Javascript function validateForm() { var result; var keywords = document.querySelectorAll('#keywords'); [].slice.call(websites).forEach(function(website) { if (website.value == '') { ...

Queueing up file downloads through a web browser

When trying to download multiple files from a server, I am required to queue them up instead of downloading in parallel. Unfortunately, I do not have access to the download server, so my only option is to work with the browser. Is there an API available t ...

Is it possible to authenticate both users and admins within the same collection in Mongoose when using Node.js with Express? Can aggregation be used for this purpose?

this is my custom schema const mongoose = require ('mongoose'); const adminSchema = new mongoose.Schema({ name:String, password:String, user:[{ name:String, email:String, password:String } ] }) var ...

Utilize node.js to run a local .php file within a polling loop

Here is the purpose of my application in brief. I am using a PHP file to read data via an ODBC connection and then write that data to a local database. This PHP file needs to be executed LOCALLY ON THE SERVER every time a loop is processed in my node.js, ...

Having trouble developing a custom jQuery tool for textareas

I am currently attempting to customize this script that mimics the Word 2007 minibar within a textarea. My approach involves encapsulating it in a plugin, but I am encountering an issue where it does not function properly with multiple textareas. If you w ...

React-highcharts: I'm encountering a difficulty with the "renderer" and I am seeking a solution to update the "state" when a function is called

Currently, I am encountering an issue with the scope of the state variable within a react application. I am in the process of adding buttons to my chart component located at the top of the high chart component. What I aim to achieve is placing these butto ...

Encountering complications when importing TypeScript declarations

I am facing a problem with importing declarations from an extended file (I am utilizing this typing). As per the example, I have included this code in my project: import * as SockJS from 'sockjs-client'; import BaseEvent = __SockJSClient.BaseEve ...

Accessing MongoDB Collection with AngularIncorporating Angular to

My MongoDB Collection has the following structure: { "Auftragsnr" : "456", "Positionnr" : "Babba Jabba Frabba", "__v" : 0, "_id" : ObjectId("53d8ef77888a15ed69dd16a5") } { "Auftragsnr" : "123", "Bonusposition" : "test", "Geschaeftsfeld" : "test3", "Posit ...

How can I retrieve Json array data in android studio using volley?

Here is a JSON encoded array provided below:- { "imager": [{ "title": "Guru", "images": ["images\/6.png", "images\/androidIntro.png", "images\/barretr_Earth.png"] }] } The issue at hand is that I need to extract each image from th ...

"Attempting to access a variable defined in one pipe results in it being undefined in a

Currently, I am utilizing gulp to process pages for a website. Some of these pages are PHP files, however, after going through the template engine, they all end up with a .html file extension. My intention is to add a property to each file indicating if it ...

Converting JSON information into a table format for easy viewing

How can I extract the first timestamp value from the initial row using C# along with Newtonsoft.Json? Is it possible to showcase this information in a table comprising of headers such as beaId, bfiId, timestamp, beaName, and bfiName utilizing Angul ...

Unable to switch checkbox state is not working in Material UI React

I am experiencing an issue with the Material UI checkbox component. Although I am able to toggle the state onCheck in the console, the check mark does not actually toggle in the UI. What could be causing this discrepancy? class CheckboxInteractivity exten ...

Tips for improving performance on AJAX-based websites with unreliable networks

During my recent travels, I have come across an issue with the way Ajax constructs websites. While I understand that requesting only necessary pieces of a webpage is efficient for servers, in areas with intermittent or limited signal, sites using this mode ...

Removing a specific row in a database table and sending a boolean indicator to an API, all while keeping the original object intact

I'm currently working on a spa project using AngularJS and integrating an api with mvvm in C#. One issue I am facing is that when I click the delete button, it deletes the line but I only want to change a boolean flag to true on the server side while ...

Incorporating Keyboard Features into Buttons

How can I toggle the page selectors in #pageList using a keyboard shortcut instead of clicking on the .togglePL button? I've tried looking up solutions online and asking questions here, but haven't found a working solution yet. Below is the code ...

Learning how to implement react-toastify promises with axios is a valuable skill to have

// I am trying to implement toastify promises to show a spinner while fetching data and then display a success or failed message // However, I am encountering an error in the code below const fetchData = () => { axios .get("https://restc ...

How can I add an SVG tooltip that appears when I hover my

I have successfully implemented an SVG map showing marked locations and polygons, with CSS styling that makes the areas stand out on hover. I achieved this without using any JavaScript code. My next goal is to create a hovering window or tooltip that disp ...

Switching back and forth between two buttons using JavaScript

In my web application, I have multiple post containers, each containing two elements: Like and dislike buttons. These buttons are designed to toggle between classes when clicked. The issue I'm currently facing is if a user likes a post and then tries ...