0

This is my first exercise in angular8. I am on the attempt to make a form that consumes an API written in springboot. The api written in spring-boot is never executed when trying to consume it from angular8 and here is the endpoint

http://localhost:8080/api/startreg




@PostMapping("/startreg")
    public ResponseData<Activity> addReg(
            @RequestParam(value="firstDate") String firstDate,@RequestParam(value="secondDate") String secondDate
            ,@RequestParam(value="username") String username) {

            try {

Here is the service.ts script

private baseUrl = 'http://localhost:8080/api/startreg';
createReg(activity: Object): Observable<Object> { 
    return this.http.post('${this.baseUrl}', activity);
  }

the html file of the angular8 is shown

<form (ngSubmit)="onSubmit()">

              <div class="col-md-3 col-sm-5 col-xs-12 gutter">
                <div class="sales">
                  <h2>From:</h2>
                  <div class="btn-group">              
                   <select [(ngModel)]="activity.firstDate" class="form-control" name="firstDate"> 

when I attempt to submit the form, from the browser console below error

HttpErrorResponse {headers: HttpHeaders, status: 404, statusText: "Not Found", url: "http://localhost:4202/$%7Bthis.baseUrl%7D", ok: false, …}

Please where I am getting it wrong

Kingston
  • 41
  • 6

1 Answers1

0

Because this.http.post('${this.baseUrl}', activity); won't invoke service with the value of this.baseUrl, you can find out why according to the error message. The URL you passed to post is still a string not a variable.

Please modify service.ts as follows:

...
    return this.http.post(this.baseUrl, activity);
}

UPDATE

Another problem is your service consumes request parameters, so you have to pass these URL arguments for HTTP request in service.ts.

The valid URL should look like this:
http://localhost:8080/api/startreg?firstDate=XXX&secondDate=XXX&username=XXX

But I am not familar with TypeScript, so I don't know how to do this. Maybe you can refer to Angular2 - Http POST request parameters.

BTW, I strongly recommend that you should use @RequestBody rather than @RequestParam for your POST service.

LHCHIN
  • 3,679
  • 2
  • 16
  • 34
  • Yes, as expected. Because your service accepts request parameters but you didn't send them in `service.ts`. – LHCHIN Oct 25 '19 at 08:10
  • please how do I send them and how do I return the response back to angular of successful entry. Much Thanks sir – Kingston Oct 25 '19 at 08:13