Search code examples
angularhttpclientangular5angular2-services

How to send POST in angular5 with multiple params?


I'm working in angular5 simple project (front end) and back end(spring boot) , i want to send a post request to the api rest with 2 parameters idPerson , and idProject , so the api rest can affect the project to the selected Person , i tried doing this in a service with POST but it's not possible .

This is the code for ProjectService.ts

    addProjToClient(idPerson:number,idProject:number){
    if(this.authService.getToken()==null) {
      this.authService.loadToken();
    }
    return this.http.post(this.host+"/saveProjectToClient",idPerson,idProject,{headers:new HttpHeaders({'Authorization':this.authService.getToken()})});

  }

It's not possible to send more than 2 parametrs in http Post , i use httpClient .

Any idea on how to do this ?


Solution

  • The second argument to http.post is the body of the post request. Just put both values in the body and then get them out of the body on the server.

    return this.http.post(this.host+"/saveProjectToClient", {
      idPerson,
      idProject,
    }, {
      headers:new HttpHeaders({
        'Authorization': this.authService.getToken()
      })
    });
    

    On the server (Springboot)

    public class Dto {
        private String idPerson;
        private String idProject;
    }
    
    
    @Controller
    @RequestMapping("/")
    public class ExampleController {
    
       @PostMapping("/saveProjectToClient")
       public ResponseEntity postController(@RequestBody Dto dto) {
          System.out.print("Person Id was: ");
          System.out.println(dto.idPerson);
          System.out.print("Project Id was: ");
          System.out.println(dto.idProject);
    
          return ResponseEntity.ok(HttpStatus.OK);
        }
    }