Home > Net >  Spring boot sends email but Angular does not. How to connect methods correctly?
Spring boot sends email but Angular does not. How to connect methods correctly?

Time:03-20

Spring Boot and Angular crud methods are ok, but still not clear how to bind other methods between spring boot and angular.

Rest API, Spring Boot-Angular. Sending email.

REST Controller

@PostMapping("/sendEmail")
public ResponseEntity<String> sendEmail(@PathVariable long id) throws CustomerNotFoundException{
    Customer customer = customerService.findCustomer(id);
    emailService.sendSimpleEmail(customer.getEmail(),
            "Hi dear customer! Your order is "  
                   "ready to pick up","Your order is waiting for you"
            );

    return new ResponseEntity<>("mail sent successfully", HttpStatus.OK);
}

Angular. Service class with http.

 sendEmail(id:any):void {
    const url = 'http://localhost:8080/customers/sendEmail';
    this.http.post(url,{responseType: 'text'}).subscribe(
      res=>{location.reload();},
      err=> {
        alert('An error has occurred while sending email')
      }
    )
  }

Thank you in advance.

CodePudding user response:

Assuming CORS has been configured your endpoint also expects id.

Add {id} to your endpoint.

@PostMapping("/sendEmail/{id}")
public ResponseEntity<String> sendEmail(@PathVariable long id) throws CustomerNotFoundException{
    Customer customer = customerService.findCustomer(id);
    emailService.sendSimpleEmail(customer.getEmail(),
            "Hi dear customer! Your order is "  
                   "ready to pick up","Your order is waiting for you"
            );

    return new ResponseEntity<>("mail sent successfully", HttpStatus.OK);
}

Add / and param id to the end of your url.

id = 123;

 sendEmail(id:any):void {
    const url = 'http://localhost:8080/customers/sendEmail/'   id;
    this.http.post(url,{responseType: 'text'}).subscribe(
      res=>{location.reload();},
      err=> {
        alert('An error has occurred while sending email')
      }
    )
  }
  • Related