3

I am rather new to Angular and now am upgrading from "the old" Http API to the new HttpClient API.

Therefor I have to use the new HttpHeaders and HttpParams, which works fine so far. But the Declaration examples I could find seem kinda odd to me, because it basically boils down to this.

let searchParams = new HttpParams();
searchParams = searchParams.append('query', query);
searchParams = searchParams.append('sort', sort);
searchParams = searchParams.append('order', order);

const headers = new HttpHeaders({
  'Content-Type': 'application/json',
  'Authorization': 'Bearer ' + user['sessionToken']
});

Is there no way to declare HttpParams in a way similar to HttpHeaders? The way I used was the only way I could find on the net and after extensive try-and-error seems like the only way that works.

I am NOT asking how to set HttpParams, I am wondering why HttpParams and HttpHeaders cannot be set in the same way (the way that HttpHeaders are set in my example, declaration in one line).

Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488
Samarek
  • 444
  • 1
  • 8
  • 22
  • 1
    If you're asking why the developers of Angular decided to do it that way, you'd have to ask *them*. That's not really a question for SO. Note that you can use `fromObject` in the options parameter (see https://github.com/angular/angular/blob/8a0e45826a4f140e9330d57594c338276a151401/packages/common/http/src/params.ts#L84), but you can't pass it straight to the constructor - `const params = new HttpParams({ fromObject: { query, sort, order } });`. – jonrsharpe Dec 21 '17 at 15:42

1 Answers1

4

In Angular@5 you can set parameters in the same way as headers like this:

let searchParams = new HttpParams({
    fromObject: {
        query: query,
        sort: sort,
        order: order
    }
});

const modified = req.clone({params: searchParams});

Or you can use setParams method on a request directly:

const modified = req.clone({setParams: {'query': query, 'sort': sort, 'order': order}});

If you're curious about why HttpParams and HttpHeaders are immutable, check this answer Why do most classes of the HttpClient API define immutable objects?

Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488
  • thanks for the help, this looks good, but I keep getting >Argument of type '{ fromObject: [...] }' is not assignable to parameter of type '{ fromString?: string; encoder?: HttpParameterCodec; }'.< as an error. – Samarek Dec 22 '17 at 09:18
  • @GeneDoe, sure, you're welcome. What version of Angular are you using? The option with `fromObject` is available in v5 and above. Try the other one with `setParams` – Max Koretskyi Dec 22 '17 at 09:25
  • 1
    ah that explains it, I am still below v5. Thanks so much again. – Samarek Dec 22 '17 at 10:15
  • @GeneDoe, you're welcome, good luck! – Max Koretskyi Dec 22 '17 at 10:16