Authenticating with HTTP
Let's consider that we are working with a backend API that expects all requests to include a custom header named Authorization
. In this case, we should refactor the HeroService
methods to include this header in each HTTP request. For example, the getHeroes
method should transform into the following:
getHeroes(): Observable<Hero[]> { return this.http.get<Hero[]>(this.heroesUrl, { headers: new HttpHeaders({'Authorization': 'myAuthToken'}) }); }
For the sake of simplicity, we are using a hardcoded value for the authentication token. In a real-world scenario, we may get it from the local storage of the browser or some other means.
All HttpClient
methods that we have met so far accept an optional object as a parameter that is used to pass additional options to a request. These options can be a custom header, as in our case, or even query...