This Angular component tries to load data from a wrong URL to simulate an error. It shows a red error message when the HTTP call fails.
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';
@Component({
selector: 'app-error-demo',
template: `
<button (click)="loadData()">Load Data</button>
<p *ngIf="errorMessage" style="color: red;">{{ errorMessage }}</p>
<pre *ngIf="data">{{ data | json }}</pre>
`
})
export class ErrorDemoComponent {
data: any = null;
errorMessage = '';
constructor(private http: HttpClient) {}
loadData() {
this.errorMessage = '';
this.data = null;
this.http.get('https://jsonplaceholder.typicode.com/invalid-url')
.pipe(
catchError(err => {
this.errorMessage = 'Failed to load data: ' + err.message;
return throwError(() => new Error(err.message));
})
)
.subscribe({
next: res => this.data = res,
error: () => {}
});
}
}