Here is my code:
import { HttpClient, HttpErrorResponse, HttpHeaders } from \'@angular/common/http\';
Angular 8 HttpClient Service example with Error Handling and Custom Header
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Student } from '../model/student';
import { Observable, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class ApiService {
// API path
base_path = 'http://localhost:3000/students';
constructor(private http: HttpClient) { }
// Http Options
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
}
// Handle API errors
handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', error.error.message);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.error(
`Backend returned code ${error.status}, ` +
`body was: ${error.error}`);
}
// return an observable with a user-facing error message
return throwError(
'Something bad happened; please try again later.');
};
// Create a new item
createItem(item): Observable<Student> {
return this.http
.post<Student>(this.base_path, JSON.stringify(item), this.httpOptions)
.pipe(
retry(2),
catchError(this.handleError)
)
}
....
....
Check complete example tutorial here
I struggled with this for a long time. I am using Angular 6 and I found that
let headers = new HttpHeaders();
headers = headers.append('key', 'value');
did not work. But what did work was
let headers = new HttpHeaders().append('key', 'value');
did, which makes sense when you realize they are immutable. So having created a header you can't add to it. I haven't tried it, but I suspect
let headers = new HttpHeaders();
let headers1 = headers.append('key', 'value');
would work too.
First, you need to add HttpHeaders with HttpClient
import { HttpClient,HttpHeaders } from '@angular/common/http';
your constructor should be like this.
constructor(private http: HttpClient) { }
then you can use like this
let header = new HttpHeaders({ "Authorization": "Bearer "+token});
const requestOptions = { headers: header};
return this.http.get<any>(url, requestOptions)
.toPromise()
.then(data=> {
//...
return data;
});