Currently, I am utilizing Angular 16 HttpClient to make requests to external services using a standard configuration:
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Tutorial } from '../models/tutorial.model';
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';
const baseUrl = 'http://localhost:8080/api/tutorials';
@Injectable({
providedIn: 'root',
})
export class TutorialService {
headers = new HttpHeaders().set('Content-Type', 'application/json');
httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };
constructor(private http: HttpClient) { }
handleError(error: HttpErrorResponse): Observable<never> {
console.error('An error occurred:', error);
// You can throw an error or return an observable here
return throwError('Something went wrong'); // Example of returning an observable with an error message
}
getAll(): Observable<Tutorial[]> {
return this.http.get<Tutorial[]>(baseUrl, this.httpOptions).pipe(catchError((e: any) => this.handleError(e)));
}
get(id: any): Observable<Tutorial> {
return this.http.get<Tutorial>(`${baseUrl}/${id}`, { headers: this.headers });
}
The issue arises when the request fails and I receive a vague Http failure response for http://localhost:8080/api/tutorials: 0 Unknown Error message in the console. https://i.sstatic.net/Fa3Ce.png