Utilizing Angular to send intricate objects through HTTP POST requests

Service Inquiry

 public submitBooking(createBooking: CreateBooking) {
    const body = this.constructRequestBody(createBooking);
    return this.httpClient.post(this.baseUrl + 'Save', body )
               .subscribe();
}

private constructRequestBody(createBooking: CreateBooking): any {

    const body = {
        'Booking': {
            'Header': this.prepareHeaderInfo(createBooking),
            'Items': [this.generateBookingItems(createBooking)],
        },
        'TestOnly': !environment.production,
    };

    this.Logger.log(body);
    return body;
}


private generateBookingItems(createBooking: CreateBooking): any {
    const bookingItem = {

        'CountryOfOrigin': createBooking.booking.countryoforigin,
        'VehicleValue': createBooking.booking.valueofvechicle,
        'SerialNumber': createBooking.booking.bookingNumber,
        'Description': createBooking.booking.description,
        'Mobility': createBooking.booking.mobility,
        'Currency': createBooking.booking.currency,
        'Weight': createBooking.booking.weight,
        'Year': createBooking.booking.year,
        'Cbm': createBooking.booking.cbm,

        //Encountering issue with the SubUnits array.
        'SubUnits':[
            createBooking.booking.relatedVehicles.forEach(element => {
                const units = {
                    'RelationType': element.relation,
                    'Weight': element.weight,
                    'Year': element.year,
                };
            })],
    };

    return bookingItem;

The SubUnits array is always empty in the request sent to WEB API. How can I iterate through the array and create objects for the request body.

Note: The structure of my angular model differs from the objects expected by the WEB-API.

I attempted using JSON.Stringify(unitsArray) without success for SubUnits

const unitsArray = [];

createBooking.booking.relatedVehicles.forEach(element => {
        const units = {
            'RelationType': element.relation,
            'SerialNumber': element.chassisno,
            'Weight': element.weight,
            'Year': element.year,
        };
        unitsArray.push(units);
    });
SubUnits : JSON.stringify(unitsArray); // This approach also did not resolve the issue with the API.

Version Info: Angular 5 Typescript 2.4.2

Answer №1

const bookingItem = {
...
    'SubUnits': [
        createBooking.booking.relatedVehicles.forEach(element => {
            const units = {
                'RelationType': element.relation,
                'Weight': element.weight,
                'Year': element.year,
            };
        })
    ]
...
};

The current loop does not populate the array in bookingItem.SubUnits. Since Array.forEach does not return a value and the variable units is never used, consider using Array.map instead.

'SubUnits': [
    createBooking.booking.relatedVehicles.map(element => ({
        'RelationType': element.relation,
        'Weight': element.weight,
        'Year': element.year
    }))
]

This will create an array with one element from

createBooking.booking.relatedVehciles
, as seen in your original post.

Answer №2

Instead of using JSON.stringify, have you attempted to simply use:

  SubUnits :unitsArray;

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

Converting JSON data into a structured format

I've encountered JSON parsing challenges when dealing with structures that have dynamic keys. For example, how can I parse JSON data like this: { "count": 2, "results": [{ key: "workspaces", id: "10" }, { key: "workspaces", id: "11" }], "works ...

Updating the selected state of an Angular 2 material mat-chip

Attempting to update the selected property of a chip named "chip" results in an ExpressionChangedAfterItHasBeenCheckedError when changing the binding property. HTML <mat-chip-list> <mat-chip *ngFor="let w of weekDays" [selectable]="tru ...

Upon initialization, Angular's BehaviorSubject is encountered as undefined

I am in the process of trying to create a fresh BehaviorSubject that is of the type ICar (which I have defined) in a service, with the initial value being either null or undefined. However, when I attempt to change the type to ICar | undefined, I encounter ...

React/Typescript/VScode - a '.tsx' extension cannot be used at the end of an import path

I have successfully converted a series of React projects to TypeScript, but I am encountering a specific issue with one non-webpack project. The error I am facing is 'an import path cannot end with a .tsx extension'. For example, this error occur ...

What is the correct way to extract results from an Array of Objects in Typescript after parsing a JSON string into a JSON object? I need help troubleshooting my code

Here is my code for extracting data from an array of objects after converting it from a JSON string to a JSON object. export class FourColumnResults { constructor(private column1: string, private column2: string, private column3: string, priv ...

Converting a tree structure from GraphQL to JSON format using JavaScript

I'm attempting to convert my client-side data from this structure: [{ id: 1, name: "dad", parent: [], children: [{ id: 2, name: "child1", parent: { parent: 1 } }, ...

Fixing vulnerabilities in npm requires Angular 7, but implementing them in an Ionic 3 project may lead to further complications

I have a query related to my Ionic 3 project. Upon running npm audit, I found 10 vulnerabilities that need to be fixed. However, both fixes require Angular 7, and I am aware that Ionic 3 only supports Angular 5. My question is, is there a way to address t ...

Creating Authorization for JSON API in Rails

Hi everyone, I've been struggling with figuring out how to authorize my JSON API. I successfully created an API for reviews, but when I call the reviews endpoint [using a token], it displays all the reviews in the database. I want to only show reviews ...

At a specific duration of inactivity on the website, I am automatically redirected to the login page due to session expiration

When I navigate through the URL based on the session, the session will expire if the user is inactive on the site. The issue arises when a user is considered inactive because the session expires after a certain period of inactivity and then redirects to th ...

Experiencing the "Method Not Allowed" issue while utilizing ASP.NET Web API within ASP.NET Web Forms

I have been working on incorporating HMAC authentication into my ASP.NET web forms application using the code provided at this link: . To integrate this code, I created a folder named "HMACAPI" and added the controllers and filters inside it. Additionally ...

A guide on integrating ngrx-store with a canLoad guard for optimal functionality

Is this a recommended practice? Below is what I am attempting to do: I have two lazy loaded modules: ManagementModule and ConfigurationModule, with the following route configuration: const routes: Routes = [ {path: '', redirectTo: 'manag ...

Surprising outcomes encountered while utilizing jq for selecting objects

When I include the body in the output list, some incorrect names are displayed. I was expecting it to only show the names for the NFL subreddit in both examples. Is this a feature or a bug? How can I ensure that only the tuples for the subreddit nfl are ou ...

Error: unable to locate module that was imported from

Every time I try to run the project using this command, an error pops up: > npm run build npm info using <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c7a9b7aa87fee9f1e9f0">[email protected]</a> npm info using ...

Warnings about NgZone timeouts are displayed in Chrome DevTools even though the timeouts are actually executing outside of the

Is it common to receive a warning in Chrome DevTools like this? [Violation] 'setTimeout' handler took 103ms zone.js:1894 even when all timeouts are executed outside of ngzone? I personally follow this approach: this.zone.runOutsideAngular(() = ...

Building a live chat streaming platform utilizing SignalR with C# and Angular for real-time communication

Currently, I am in the process of building a chat application using C# and Angular. Within my C# controller lies a unique Text Generative Algorithm that generates responses based on user input from the frontend. These responses are generated in chunks, and ...

With TypeScript, you have the flexibility to specify any data type in the generic types when using the axios.get method

axios.get('/api') When working with TypeScript as shown above, it is important to designate types for better clarity. This allows us to reference the type definition of axios, like so: (method) AxiosInstance.get<any, AxiosResponse<any> ...

Make sure to verify the existence of nested keys in the video object within the YouTube API to prevent encountering a NULLPOINTER

I am looking to verify the presence of a nested key in the Video object that is returned as a JSON response from a YouTube video search. The code snippet I'm using for this task is: YouTube.Videos.List searchvideostats = youtube.videos().list("snippe ...

Updating the mat-icon in a row when a button is clicked

I am currently working on implementing the mat-table in my project. I am facing an issue where I need to change the mat-icon of a button based on a click event, but I only want this change to apply to a single row in the table. At the moment, I am able to ...

Implementing Azure Active Directory version 2 (AAD V2) in an ASP.NET Core Web

Looking for assistance with a problem I'm facing. I am currently developing a webapi in .netcore using VS2017, and I am attempting to implement the new authentication model with . I have registered the application and set up the reply URL to https:// ...

I am facing an issue where certain Material icons are not displaying properly in my Angular project

I am encountering a problem in my Angular project where some Material icons are not displaying properly: <mat-icon>domino_mask</mat-icon> <mat-icon>hourglass</mat-icon> Interestingly, all other icons appear as expected. I have take ...