BadRequest 400 HttpParams Angular 4.3

0

I'm using the new angle library to make requests, HttpClient . Along with the angled 4+ I am using here in the enterprise for the backend , Java with Spring (boot).

The problem is occurring at the time of making a GET request for the backend , the HttpParams , used with HttpClient to pass parameters, does not replace of the variables and thus the backend deny the request.

URL backend (Java): controller/obterByCodOne/{codOne}/codTwo/{codTwo}

Ex: URL frontend (Angular): http://localhost:8080/controller/obterByCodOne/:codOne/codTwo/:codTwo

Code:

let params = new HttpParams()
            .set('codOne', codOne)
            .set('codTwo', codTwo);

Result (wrong): http://localhost:8080/controller/obterByCodOne/:codOne/codTwo/:codTwo?codOne=valueA&codTwo=valueB

HttpParams is not replacing the variable, but concatenating.

In other AngularJS projects, the value was usually replaced with $resource . Instead of having to concatenate chunks of URLs with the variables until you get to a final result.

Anyway ... I'm in this mess. Either I'm not understanding the use of HttpParams or I'm not sure how to use it.

    
asked by anonymous 04.12.2017 / 16:06

3 answers

0

Since my URLs were in a standard URLS file, I could not concatenate them. I end up adopting a pattern for my URLs and each parameter is followed by a colon, for example: and in my service I give a replace. In the backend in Java I use @Pathvariable in my parameters, where q @RequestMapping I used my url so link {idA} / {nameB}.

In this scenario, the parameters must be mandatory. In a filter case with optional parameters I adopt the practice of using DTO (Data Transfer Object).

I hope to help you too!

    
29.12.2017 / 13:36
1

This problem has already occurred to me. If I can not use HttpParams, do a String manipulation and manually add the params. ex:

  public getPessoas(idade){

       this.http.get(URL_API+"?idade="+idade)
       ...
  }

obs.:

  • URL_API - It's the api url
  • "age" - This is the manual way to add a parameter.
  • age - variable representing the value I'm passing as a parameter.

If you want to add a new parameter, add a "&" and pass the new parameter. ex:

this.http.get(URL_API+"?idade="+idade+"&peso="+peso)

This is not the best solution, but it works! Hope it helped :)

    
04.12.2017 / 18:06
1

The HttpParams are QueryParams , the parameters of url ? .

Use TypeScript String Interpolation to build your url.

get(codOne: number, codTwo: number): Observable<any> {
  return this.httpClient.get('http://localhost:8080/controller/obterByCodOne/${codOne}/codTwo/${codTwo}');
}
    
05.12.2017 / 13:59