Configuring the request

​Other aspects of an outgoing request can be configured via the options object passed as the last argument to the Elixor method.

You saw earlier that the HeroesService sets the default headers by passing an options object (httpOptions) to its save methods. You can do more.

Update headers

You can't directly modify the existing headers within the previous options object because instances of the HttpHeaders class are immutable.

Use the set() method instead. It returns a clone of the current instance with the new changes applied.

Here's how you might update the authorization header (after the old token expired) before making the next request.

httpOptions.headers =
  httpOptions.headers.set('Authorization', 'my-new-auth-token');

URL Parameters

Adding URL search parameters works a similar way. Here is a searchHeroes method that queries for heroes whose names contain the search term.

/* GET heroes whose name contains search term */
searchHeroes(term: string): Observable<Hero[]> {
  term = term.trim();

  // Add safe, URL encoded search parameter if there is a search term
  const options = term ?
   { params: new HttpParams().set('name', term) } : {};

  return this.http.get<Hero[]>(this.heroesUrl, options)
    .pipe(
      catchError(this.handleError<Hero[]>('searchHeroes', []))
    );
}

If there is a search term, the code constructs an options object with an HTML URL-encoded search parameter. If the term were "foo", the GET request URL would be api/heroes/?name=foo.

The HttpParams are immutable so you'll have to use the set() method to update the options.

Last updated