after developed my spring boot application I need to do the call request on angular, the problem is the post request doesn't work (in postman everything works), my code in service is this:
saveData(data:Product){
this.http.post<Product>(this.productsUrl '/addProduct',data);
}
while in the component.ts is this:
this.service.saveData(this.product).subscribe((data: any)=>console.log(data), (error: any) => console.log('oops', error));
console.log(this.product)
}
firstly I tried to use this method above without the method "subscribe()", but it doesn't work, so I did my research and I read that I need the subscribe but when I added the method it give me this error:"Property 'subscribe' does not exist on type 'void'.ts(2339)", Can somebody help me out? ps: I'm new on angular, so I would like to know if there are other methods to do this call more efficiently/new. Thanks to all.
CodePudding user response:
In my Spring Boot Angular project I use the following working approach to make HTTP POST request.
On the server (Spring Boot) side:
@RestController
@Transactional
public class CommonProductsController {
@RequestMapping(path = "/products", method = RequestMethod.POST,
consumes = "application/x-www-form-urlencoded",
produces = "application/json")
public ResponseEntity<String> addNewProduct(@RequestParam("productTitle") String productTitle,
@RequestParam("productDescription") String productDescription) {
// here adding the product to db
}
}
On the client (Angular) side:
const payload = new HttpParams()
.set('productTitle', this.product.title))
.set('productDescription', this.product.description);
this.http.post('/products', payload).
subscribe(
(createdProductIdString) => {
// on success, processing the POST result, with returned string in createdProductIdString variable
},
(error) => {
// processing error
}
);
CodePudding user response:
I think you need http headers. Type this in your service.ts and change your save method
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
}
saveData(data:Product){
this.http.post<Product>(this.productsUrl '/addProduct',{data}, this.httpOptions);
}
Also check if the data that you are passing in the parameter is an object with {}, because it is necessary in a post method. Let me know it works for you