Reputation: 157
I have a post method on the backend ( Spring boot ) that returns the id
when I post data.
@RequestMapping(value="/fncs", method=RequestMethod.POST)
public int addFnc(@RequestBody Fnc fnc){
fncservice.addFnc(fnc);
return fnc.getN_fnc();
}
I want to create a function in angular service that return me the id
(number) ,I tried it with this function but it didn't work.
const baseUrl = 'http://192.168.100.9:8081/fncs';
create(data): Observable<any> {
return this.http.post(baseUrl, data);
}
I carried out the work of the function
Upvotes: 1
Views: 1591
Reputation: 19173
This should work in your case. However it is not considered best practice to return directly an integer from a Rest Api. You should consider to wrapp it inside a JSON object.
create(data): any {
this.http.post(baseUrl, data, { responseType: 'text'})
.subscribe((res) => {
//response will be parsed as text and we need to convert it to int
const resInt = + res;
console.log(resInt);
return resInt;
},
(error) => {
console.log(error);
}
)
}
I doubt you need it as it is here. However you can check that this will work in your case of seeing the response. Actually you need to use the subscribe method not here on the service but wherever you want to do something with the response.
Upvotes: 1
Reputation: 381
You could just add the ".subscribe" method to receive the data after finishing the post request and dealing with the coming output like this:
create(data): any{
this.http.post(baseUrl, data).subscribe({
next: data=>{
return data
},
error: error => {
return 0
}
})
}
Upvotes: 1