import { Component } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
data: any;
errorMessage: string;
constructor(private http: HttpClient) {}
getData() {
this.http.get('/api/data').pipe(
catchError((error: HttpErrorResponse) => {
if (error.status === 404) {
this.errorMessage = 'Resource not found';
} else if (error.status === 500) {
this.errorMessage = 'Internal server error';
} else {
this.errorMessage = 'Unknown error occurred';
}
return throwError(this.errorMessage);
})
).subscribe((response) => {
this.data = response;
});
}
}
In this example, the AppComponent class defines a getData method that sends an HTTP GET request to /api/data and handles the response using the subscribe method.
The subscribe method takes two functions as arguments: a success handler function and an error handler function. In this example, we only define the success handler function, which sets the data property of the component to the response.
The error handler function is defined using the catchError operator, which catches the error thrown by the HTTP request and checks the error status code. If the status code is 404, it sets the errorMessage property of the component to “Resource not found”. If the status code is 500, it sets the errorMessage property to “Internal server error”. If the status code is any other value, it sets the errorMessage property to “Unknown error occurred”.
The catchError operator returns a new observable that emits the error message using the throwError function. This ensures that the error is propagated to the next error handling operator in the observable chain, or to the subscribe function if there are no further error handling operators.