Elad Benda Elad Benda - 2 months ago 17
TypeScript Question

how can i send 2 object in angular2 post request

I have this code:

client side (angular2)

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)
);
}


and

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 know how to send one object in post, but how can i send 2 object in post request?

Answer

Since you are using Json as your media, it is technically impossible to achieve this, as two separate arbitrary objects in a single document would be invalid Json.

However, a potential solution here would be to create an object that wraps these two objects.

Request Object

public SaveConfigRequest {
    private MyObj myObject;
    private CountryGasStationConfig countryGasStationConfig;


    //getters and setters
}

New Method Signature

public void saveConfig(SaveConfigRequest request)

Example Json Document

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