Search code examples
angularangular2-http

How to set HttpParams in a compact way similar to HttpHeaders in Angular


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).


Solution

  • 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?