David D. David D. - 9 months ago 90
HTTP Question

Query params has no effect with Angular2+

I followed many tutorials to try make query parameters work with Angular2+ (using the old

Http
module, not the new
HttpClient
module)

Here is what I got:

import {Injectable} from '@angular/core';
import {Http} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/timeoutWith';

getCurrentServiceMenu(till: Till) {
const myParams = new URLSearchParams();
myParams.set('till_uuid', till.uuid);

return this.http.get(
wsGetCurrentServiceMenu.url,
{
params: myParams,
headers: this.authService.getAuthorizationHeader(),
})
.timeoutWith(timeout, Observable.throw(''));
}


It makes no error, but has no effect : there is no parameter in the query.

I'm using Angular 5.0.0 with rxjs 5.5.2

Answer Source

import angular's URLSearchParams class

import { Http, URLSearchParams } from '@angular/http';

You are using the native javascript URLSearchParams


Alternatively you could use the native javascript class, however you need to convert it to a string.

return this.http.get(
    wsGetCurrentServiceMenu.url,
    {
        params: myParams.toString(),
        headers: this.authService.getAuthorizationHeader(),
    })
    .timeoutWith(timeout, Observable.throw(''));

This confusion is what probably led the angular team to use HttpParams as a replacement in the new HttpClient

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download