Transitioning from using static data sets for cascading dropdowns in Angular 4 to fetching a dynamic object from a web API request

When starting a new project involving .net core and Angular 4, I had to wait for the implementation of a real database.

Now that the database is in place, a DBA and backend developer have created a web api from which I need to retrieve a nested object containing data that was previously stored in simple arrays.

Current Data calls

Here is where I execute a method to fetch all the categories

getCategory() {
    return [
        new Category(1, 1, 'VAMC-Cat-1'),
        new Category(2, 1, 'VAMC-Cat-2'),
        new Category(3, 1, 'VAMC-Cat-3'),
        new Category(4, 2, 'Vet-Cat-1'),
        new Category(5, 2, 'Vet-Cat-2'),
        new Category(6, 2, 'Vet-Cat-3'),
        new Category(7, 3, 'Provider-Cat-1'),
        new Category(8, 3, 'Provider-Cat-2'), 
        ...
        // additional entries omitted for brevity
    ];
}

In order to display three cascading dropdowns, I now require a single call that returns a complex object. How can I make these calls and persist the data in Angular 4/typescript? Any ideas/examples?

New Data retrieved using Swagger UI from the web api:

[
  {
    "customerTypeId": 1,
    "customerTypeName": "VAMC",
    "childCategories": [
      {
        "categoryId": 1,
                ...
                // additional entries omitted for brevity
          }
        ]
      },
            ...
            // additional entries omitted for brevity
      }
    ]
  }
]

Answer №1

Utilizing Array's map() and reduce() functions offer flexibility in implementation. Exploring filter() could also be beneficial.

Additionally, parameter destructuring is showcased here through destructive parameters.

In Angular 4, having a designated service for such operations is recommended. This service can handle API calls, data transformation, and return Promises or Observables that are manageable in the component.

let result = data.map(item => item["childCategories"])
  .reduce((a, item) => a.concat(item), [])
  .map(({
    categoryId,
    categoryName,
    customerTypeID
  }) => ({
    categoryId,
    categoryName,
    customerTypeID
  }));

To incorporate your class, modify the last map function as follows:

  .map(({
    categoryId,
    categoryName,
    customerTypeID
  }) => new Category(
    categoryId,
    categoryName,
    customerTypeID
  ));

const data = [...];
let result = data.map(item => item["childCategories"])
  .reduce((a, item) => a.concat(item), [])
  .map(({
    categoryId,
    categoryName,
    customerTypeID
  }) => ({
    categoryId,
    categoryName,
    customerTypeID
  }));
console.log(result);

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

What methods can be used to implement client-side validation on a file upload control in ASP.NET to verify if the filename includes special characters?

When working with the ASP.NET 3.5 platform, I encountered an issue while using a file upload control and an ASP button to upload files that contain special characters, such as (file#&%.txt). This caused the application to crash and display the followin ...

The usage of nextTick in Vue.js and its role in updating components

Although I am a beginner with vue.js and have a basic understanding of it, I came across a sample code utilizing nextTick() today. Trying to comprehend its purpose led me to explore the documentation, which ended up complicating things further and leavin ...

Having trouble with blockUI compatibility on Internet Explorer 11?

I have encountered an issue with a piece of code that functions correctly in Chrome and FF, but not in ie11. Interestingly enough, when I tested it in ie8, it worked perfectly fine. Has anyone else experienced similar problems with blockUI on ie11? The s ...

Retrieve data from an array and insert it into a SQL database by matching the array element with

Currently, I am attempting to send a JSON payload to SQL in order to import a specific column. Within the JSON data, there is a segment structured like this: "Custom":[ {"id":100, "value" 8 }, {"id":200, ...

A more concise validation function for mandatory fields

When working on an HTML application with TypeScript, I encountered a situation where I needed to build an error message for a form that had several required fields. In my TypeScript file, I created a function called hasErrors() which checks each field and ...

Utilizing CSS for styling a class with a dynamic name

On the server side, I am dynamically generating class names like this: <p class="level_1">List item 1</p> <p class="level_2">List item 2</p> <p class="level_3">List item 3</p> <p class="level_1">List item 1</p& ...

Issue with Angular 6 and Html Webpack Plugin

My project was recently updated from Angular 5 to Angular 6, causing some changes in the file structure. The webpack.config files are no longer present and the project now operates under CLI engage. However, I encountered an issue after the migration rela ...

Reversing a Firebase list in Angular 2 after inserting a new item: A step-by-step

I am currently looking for a solution to reverse my Firebase list in real-time. For instance: Let's say I have the following Firebase list: {apple, orange, banana}; == After reversing => {banana, orange, apple} If I were to add a new item (with ...

"Requesting data with Ajax results in an undefined value

As a beginner in Rails, I'm feeling overwhelmed by an error I can't seem to fix. The issue arises when I attempt to invoke the get_info_from_iclass method located in my rentals_controller from my JavaScript file. $('document').read ...

The remove() method in AJAX function is not functioning as expected

Within a jQuery click event that uses $.post(), I have a .remove() function inside the response callback. Strangely, the alert() seems to function correctly when the code is executed, but the .remove() does not work at all, even though the alert() in the ...

How to Use Vue.js to Find the Nearest Div Element with a Specific

Below is the HTML code I am working with: <div id="app"> <div class="image"> <div class="overlay"> <p>Some overlay text</p> </div> <img src="https://placeimg.com/640/480/any" class="img-fluid"> ...

In Python3, convert an empty string into a JSON object

When using json.loads(), attempting to pass an empty string will result in a JSONDecodeError. Python 3.6.4 (default, Jan 5 2018, 02:13:53) [GCC 7.2.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import js ...

Error with SwitchMap on ActivatedRoute.paramMap

When I try to run the ngOnInit method of my component, I encountered an error with the following line of code. this.products$ = this.route.paramMap.switchMap((params: ParamMap) => this.getProductsForType(params.get('type'))); The error mes ...

What is preventing array.map() from being a function?

I am facing an issue when trying to map an array from the useState hook in react. The error message that I am getting is: TypeError: documents.map is not a function Here is the code snippet that I am working with: const [docs, setDocs] = useState(docume ...

The styling of PrimeNG Element cannot be directly applied using the default Angular 2 ViewEncapsulation (Emulated) as it is not scoped

Attempting to utilize the styleUrls property in my Angular 2 component for leveraging View Encapsulation has presented an issue when new elements are inserted into the DOM post-Angular initialization. The problem arises with a PrimeNG paginator that lacks ...

struggling to set dropdown select value within an AngularJS controller

I'm feeling a bit puzzled about the issue I am experiencing. Let me explain. HTML <div> <select ng-model="params.select" ng-change="View($event)"> <option value="" disabled>-</option> <option val ...

Access your login page with a nodejs mongoDB connection

After successfully sending username, password, and email through postman, the information gets added to the MongoDB schema. However, on the login page in React, it doesn't seem to work correctly. Any assistance would be greatly appreciated. Thank you. ...

Issue with Alignment of Border in PDF [Example Included]

I am currently developing a straightforward react application with very minimal content. index.js: <div className="App"> <div id="printable-div"> <h1>Generate PDF</h1> <p>Capture a screenshot of ...

Angular Select Component with Input Value

In a small part of my code, I have a select tag with multiple option elements. This allows me to loop through the elements and select the one that I require. The tricky part is that I need to implement a search functionality within this select. Essential ...

Deactivate text/input field in React and Next.js based on Dropdown Selection

As a newcomer to React, I am facing an issue with disabling and enabling an input field based on the selected value in a dropdown. My tech stack includes React, Next Js, React-bootstrap, and formik. function Input(){ const [disabled, setDisabled] = useStat ...