angularhttp-parameters

Angular2 HttpParams not sent as expected


When sending a GET request with Query Parameters using Angular2 http, the sent parameters aren't sent as I expect. Rather than the standard key value pair e.g.

key1=val1&key2=val2

It's being sent as the HttpParams object e.g.

%7B%22param%22:%key1%22,%22value%22:%22val1%22,%22op%22:%22a%22%7D

*decoded: {"param":"key1","value":"val1","op":"a"}

Below is a snippet of my code:

  getAllPlayers(fantasyFormat: string, draftFormat: string): Observable<Player[]> {
    let params = new HttpParams();
    params = params.append('fantasyFormat', fantasyFormat);
    params = params.append('draftFormat', draftFormat);

    return this.http.get(this.playersUrl, {params: params})
      .map((res: Response) => res.json())
      .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
  }

Not sure what is going wrong here, seems to be consistent with other examples I've followed...


Solution

  •  getAllPlayers(fantasyFormat: string, draftFormat: string): Observable<Player[]> {
        return this.http.get(`${this.playersUrl}?fantasyFormat=${fantasyFormat}&draftFormat=${draftFormat}`)
          .map((res: Response) => res.json())
          .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
      }
    

    I'd suggest to do it like this. I don't see a need to use HttpParams here. Also I never used them in my code. I'll read about them, but it seems to me that there's no difference except syntax and URI encoding between those cases.