Is there a way to include two objects in an Angular2 post request?

This piece of code is giving me trouble:

On the client side (using Angular 2)

saveConfig(configType: ConfigTypes, gasConfigModel: GasConfigModel): any {
    console.info("sending post request");
    let headers = new Headers({
        'Content-Type': 'application/json'
    });

....

    return this.http
      .post(this.url, formParamString, ??, {headers: headers})
      .map(res => res.json())
      .subscribe(
        data => {
          console.info("next: ");
          console.info(data)
        },
        err => console.error(err)
      );
  }

Meanwhile, on the server side:

@Path("/SaveConfig")
@POST
@Consumes(MediaType.APPLICATION_JSON + ";charset=utf-8")
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
public void saveConfig(MyObj my object, CountryGasStationConfig countryGasStationConfig) throws Exception {....}

I am familiar with sending one object in a post request, but how can I send two objects in a post request?

Answer №1

As your data is in JSON format, combining two separate objects into a single document would result in invalid JSON. This poses a technical challenge.

One potential solution is to encapsulate these two objects within a wrapper object.

Request Object

public class SaveConfigRequest {
    private MyObj myObject;
    private CountryGasStationConfig countryGasStationConfig;

    //getters and setters
}

New Method Signature

public void saveConfig(SaveConfigRequest request)

Example JSON Structure

{
  "myObject": {...},
  "countryGasStationConfig": {...}
}

Answer №2

If you need to send two objects with different key values, you can combine them into one big object like this:

let obj1;
let obj2;
let obj2send={
'obj1':obj1,
'obj2':obj2
};

Now the object obj2send contains both objects.

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

Combine Rest API with JSON into BPMN for React or Angular 8 along with TypeScript compatibility

Looking for an angular or react BPMN library that supports TypeScript and REST API services without needing to parse XML. I've searched extensively but can't find a BPMN library with JSON service. I need to create a workflow similar to this us ...

How can I dynamically reference two template HTML files (one for mobile and one for desktop) within a single component in Angular 6?

Here is the approach I have taken. Organizational structure mobile-view.component.html <p> This content is for mobile view </p> desktop-view.component.html <p> This content is for desktop view </p> mobile.component.ts import ...

Are you looking for a streamlined method to create styled components with MaterialUI?

I am exploring ways to easily define convenient components in my application utilizing Material-UI. After referring to an example from the Material-UI documentation for Appbar, I attempted to incorporate some React components for better readability. My c ...

Creating an image dynamically at runtime from a section of HTML code as it appears in the browser

Is there a way to use Java API or Jquery library to create an image from input HTML code? Alternatively, how can I capture a screenshot of a section of HTML code as it appears in the browser? For example: If I have the following HTML code: <h1>Logo& ...

Converting TypeScript query string values into GUIDs

I'm currently working on a project that requires me to retrieve a string value (GUID) and convert it into a GUID. The query string format is already in GUID, but when getting the value from the query string using AngularJS and TypeScript, it returns ...

Is it possible to replicate, modify, or recycle a purely HTML and CSS component in Angular?

On my Angular website, I am looking to reuse a component across more than 30 pages. While the majority of the pages have similar CSS, the content inside varies. I know I can simply insert <app-example></app-example> on all the pages, using < ...

Setting up Apache to work with Angular 2

I am in the process of setting up a virtual host for my Angular2 application. I found an article that seems helpful: https://www.packtpub.com/mapt/book/Web+Development/9781783983582/2/ch02lvl1sec15/Configuring+Apache+for+Angular The instructions suggest ...

The Updating Issue: Angular 2 Table Fails to Reflect Value Changes

I have initialized a table with user details using the ngOnInit() method. When I click on the "create user" button, it opens a form to add a new user to the database. However, the table does not update automatically with the new user's information. H ...

Angular outputting a basic static value

After searching extensively for a solution to my issue with Angular output, I have only come across ways to emit events. In my specific scenario, I have a parent component containing a router, and I need to dynamically change the title based on a value f ...

Is there a way to implement a mask feature for a ComboBox in JavaFX?

Is there a method to implement a Mask in a ComboBox? I am trying to incorporate telephone number formatting in my ComboBox, but I am struggling to find a way to achieve it. Here is an example of a mask in Textfields: https://i.sstatic.net/w3UTS.png Essen ...

Utilize the multipart/form-data approach for sending files with Angular 6

I attempted to send two fields to a backend service. One field is a typical string, while the other is a file field. However, when I utilize the post method of the Http Client, I encounter a 500 Error from the server notifying me that the content-type is n ...

Optimize your code in Angular 5 by consolidating or restructuring numerous Subscribe calls

Currently, I am utilizing Angular 5.2 for my web project. One of the pages includes multiple subscribe calls to various webAPI methods. While these calls are distinct and retrieve different datasets, I'm contemplating if there is a method to consolida ...

I am experiencing issues with the HTTPClient call not returning accurate JSON data within my Appcelerator Titanium application

Every time I attempt to retrieve information from a JSON file, I encounter an error. function search(e){ var url = 'https://www.dotscancun.com/createjson.php?id=100001'; var xhr = Ti.Network.HTTPClient({ onerror: function(e){ ...

The functionality of the String prototype is operational in web browsers, but it encounters issues

Version: 8.1.0 The prototype I am working with is as follows: String.prototype.toSlug = function () { return (<string>this) .trim() .toLowerCase() .replace(/\s+/g, '-') .replace(/[^\w\-]+/g, '') ...

Function that yields promise result

I need help figuring out how to make this recursive function return a promise value. I've attempted various approaches, but they all resulted in the search variable ending up as undefined. public search(message: Message) { let searchResult: strin ...

Setting up ReactJS and TypeScript in a fresh MVC5 project from scratch

After extensively trying out various tutorials, I have yet to successfully run a basic MVC5 project using TypeScript and ReactJS. For reference, I have created these projects from scratch in Visual Studio 2015 with .NET 4.6.1, using the ASP.NET Web Applic ...

Displaying the Ionic loading spinner on the entire page rather than a restricted small box

Right now, I'm able to implement a basic loading effect, but it appears as a small box. presentCustomLoading() { let loading = this.loadingCtrl.create({ content: 'Loading Please Wait...' }); loading.present(); } However, I ...

When using a Redux action type with an optional payload property, TypeScript may raise complaints within the reducer

In my react-ts project, I define the following redux action type: type DataItem = { id: string country: string population: number } type DataAction = { type: string, payload?: DataItem } I included an optional payload property because there are tim ...

Error: Java - unable to access field due to conflicting initialization

I am encountering an issue and I am unsure what to call it. class test{ JButton button=new JButton("button"); JFileChooser fc=new JFileChooser() { @Override public void approveSelection(){ File f = getSelectedFile(); ...

Retrieving the input[text] value in TypeScript before trimming any special characters

One of the tasks I am working on involves a form where users can input text that may contain special characters such as \n, \t, and so on. My objective is to replace these special characters and then update the value of the input field accordingl ...