How to send a parameter (within body, no headers) from Angular to Spring Boot?

Viewed 59

How do I send this defined parameter number from Angular/typescript to Spring Boot?

Sample fragment of AngularJS/typescript code, which is making a post request to the Spring Boot Microservice:

 login(){
    let body: any = "091" //student number
    return this.http.post("http://localhost/api/users/login", body)
    //how do I post request this "091" defined parameter to the Springboot REST URL?
  }

Sample fragment of Java SpringBoot Controller file code:

@PostMapping(path = "/api")
    public Login<String>(@RequestBody Login login{
       // ??? how do I retrieve the defined body from Angular to this Spring Boot service?
    }

Sample fragment of Java SpringBoot Model file code:

public class Login{
//??? What should this code look like, if it's receiving a defined parameter from Angular?
}
1 Answers

1.Using request body

//Angular
login(){
    let request: any = {studentId : "091"} //student number
    return this.http.post("http://localhost/api/users/login", request)
  }

//Java Model
public class Login{
  private String studendId;//variable name should be same as the variable sent from angular
}

//Java Controller
@PostMapping(path = "/api/users/login")
 public Login<String> userLogin(@RequestBody Login login){
       System.out.println(login.studentId) //You can access the studentId using the login object
  }

2.Using Path variable

//Angular
login(){
    return this.http.post("http://localhost/api/users/login/091")//append studentId in the request URL
  }

//Java Controller
@PostMapping(path = "/api/users/login/{studentId}")
 public Login<String> userLogin(@PathVariable("studentId") String studentId){
       System.out.println(studentId) //You can access the studentId variable
  }

//No need of Model class 
Related