How pass json array in Angular post method and how get this array in Api?
Solved ..The problem is I have send empty Array reauestData[ ] but now
I have changed array to json object
{
"data":
[
{"columnname":"symbol","filterby":"","values":"","time":"","datatype":"String"},{"columnname":"order_Receiving_Date","filterby":"","values":"","time":"","datatype":"DateRange"},{"columnname":"event_Type","filterby":"","values":"","time":"","datatype":"String"},{"columnname":"firm_ROE_ID","filterby":"","values":"","time":"","datatype":"int"},{"columnname":"rejected_ROE_ID","filterby":"","values":"","time":"","datatype":"int"}
]
}
Post Method
component.ts
prepareData() {
console.log("this.FilterData"+JSON.stringify(this.FilterData));
this.loading = true;
this.SharedHttpClientService.post(
this.UrlsService.setAPIURl(
APIURL.Surveillance_OatsException_Summary),
this.FilterData)
.map((response: Response) => {
this.isLoadingResults = false;
this.isRateLimitReached = false;
return response.json();
})
.subscribe(Element => {
this.dataset=Element;
},
(err: HttpErrorResponse) => {
this.isLoadingResults = false;
this.isRateLimitReached = true;
});
this.loading = false;
}
service.ts
private attachAuthorization(): RequestOptions {
const headers = new Headers();
headers.append('Content-Type', 'application/json');
//headers.append('HttpHeaders.ACCEPT', 'MediaType.APPLICATION_JSON_VALUE');
headers.append ('Authorization',sessionStorage.getItem('token'));
//console.log(localStorage.getItem('token'));
const options = new RequestOptions({
headers: headers,
responseType: ResponseContentType.Json,
});
return options;
}
public post(url: string, requestData: any):Observable<any>{
const options = this.attachAuthorization();
//console.log(localStorage.getItem('token'));
let Data={"data":requestData}
console.log("Data "+JSON.stringify(Data));
return this.http.post(url,JSON.stringify(Data),options);
}
API controller Function
@RequestMapping(value = {"/Oats-Exception-summary/"}, method = RequestMethod.POST)
public ResponseEntity<List<OatsExceptionSummary>> OatsExceptionSummaryPost(
@RequestBody Map payload)throws SQLException,JSONException,Exception {
JSONObject root = new JSONObject( payload);
JSONArray dataArray = root.getJSONArray("data");
for (int t=0; t<dataArray.length(); t++) {
JSONObject JObject = dataArray.getJSONObject(t);
System.out.println(JObject.getString("columnname"));
}
String FilterData="";
//JSONObject jsonObj=new JSONObject(payload);
List<OatsExceptionSummary> Data =ISurveillanceService.getOatsExecptionSummary(FilterData);
if (Data.isEmpty()) {
return new ResponseEntity<List<OatsExceptionSummary>>(HttpStatus.NO_CONTENT);
} else {
return new ResponseEntity<List<OatsExceptionSummary>>(Data, HttpStatus.OK);
}
}
How to post an object to an array in a json using Angular 6
You have some strange things in your code. First :
In you API
return this.http.get<Test[]>("http://localhost:3000/customers", {params}).pipe(map(res => res));
I think what you want to do here is : (the pipe is useless you dont use it and it's not an array)
return this.http.get<Test>("http://localhost:3000/customers",{params});
In your component you want to push the update trainData list
submitForm(){
const lastTrainData = this.test.trainData[this.test.trainData.length-1];
const newTrainData = this.testForm2.value;
newTrainData.id = lastTrainData.id + 1;
this.test.trainData.push(newTrainData);
this.TestService.postTests(this.test);
}
Sending array of objects via POST not working - Angular
The solution is to store the data into an object, not an array. The reason is that you cannot send a JSON array to your backend if it only consumes one single object. They are incompatible.
TS
// User object
private user = {
firstName: String,
lastName: String
};
....
// Populates the user object
this.user.firstName = this.form1.controls['firstName'].value;
this.user.lastName = this.form2.controls['lastName'].value;
// Sends the form data to the service
this.data.sendFormData(JSON.stringify(this.user)).subscribe(
response => console.log("Success! ", response),
error => console.error("Error: ", error)
);
I am using multiple form groups because I am using Angular material's stepper in linear mode, which requires each step to have its own FormGroup.
More on that: https://material.angular.io/components/stepper/overview#linear-stepper
Also, I had to add a header to my POST:
My Service
private header = new HttpHeaders({ 'content-type': 'application/json' });
constructor(private http: HttpClient) { }
ngOnInit() { }
sendFormData(userData) {
return this.http.post("http://localhost:8080/createAccount", userData, { headers: this.header });
}
Good reading on converting objects to JSON VS arrays to JSON: https://alligator.io/js/json-parse-stringify/
passing a body containing a json array of items for delete in angular
you can pass body in httpdelete with options
let apiUrl = 'yourUrl';
let transactions = [{
"eventId": "21012200237172",
"productCode": "LC",
"id": "LC20110000090023"
}];
const options = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
}),
body: {
transactions: transactions
},
};
this.httpClient
.delete(apiUrl, options)
.subscribe((s) => {
console.log(s);
},err => {
console.log(err);
});
How to extract JSON Data and load into an Array in Angular 7
I Solved it by pushing the JSON Response into an Array.
Home.component.ts
public data: any;
public weather: any;
constructor(private weatherService:WeatherService) {
}
ngOnInit() {
this.weatherService.getJsonData('./assets/City.json').subscribe(data => {
this.data = data; //Reading JSON Data
this.getWeatherList(); //Calling GetWeatherList Function
});
}
getWeatherList(){
if (this.data) {
// console.log(this.data);
const dataList = this.data.List;
let tempArr : any = [];
for (let temp of dataList) {
this.weatherService.getWeather(temp.CityCode).subscribe((Response: any) => {
tempArr.push(Response.list[0]); //Pushing Response to Array
})
}
console.log(tempArr)
this.weather = tempArr; //Assigning Array to Weather Constant
}
}
Related Topics
How to Know If All the Variables in a Class Are Null
How to Split a String Between Letters and Digits (Or Between Digits and Letters)
Knowing Which Java.Exe Process to Kill on a Windows Machine
Find Everything Between Two Xml Tags With Regex
How to Have Each Record of Json on a Separate Line
Getting Column Names from a JPA Native Query
How to Open Excel File Using JavaScript Code Without Using Activex Control
Counting Unique Characters in a String
How to Run Multiple Jobs in Spring Batch Using Annotations
How to Store User Input into an Existing Array
How to Decrypt Whatsapp Database File
What Happens When Base and Derived Classes Each Have Variables With the Same Name
How to Disable Log4J Logging from Java Code
How to Map Json Field Names to Different Object Field Names
Flush/Clear System.In (Stdin) Before Reading
Spring JPA Selecting Specific Columns
Java.Lang.Noclassdeffounderror: Org/Json/Simple/Parser/Parseexception With Eclipse and Spring