import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { catchError } from 'rxjs/operators'; import { throwError } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class UserService { constructor(private http: HttpClient) {} getUser(id: number) { return this.http.get(`/api/users/${id}`).pipe( catchError(error => { return throwError(() => new Error('User not found')); }) ); } }
The catchError operator intercepts the HTTP error and returns a new error with the message 'User not found'. So the component will receive this new error, not the original HTTP error.
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { catchError, of } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class DataService { constructor(private http: HttpClient) {} fetchData() { return this.http.get('/api/data').pipe( // error handling here ); } }
Option A returns an observable of a fallback object using of(). Option A returns a plain object, which is invalid. Option A rethrows an error, not a fallback value. Option A returns undefined, causing errors.
getData() {
this.http.get('/api/data').subscribe({
next: data => console.log(data),
error: err => console.error('Error:', err)
});
return this.http.get('/api/data').pipe(
catchError(err => {
console.log('Caught error');
return of([]);
})
);
}The first HTTP call subscribes directly without catchError, so errors from that call are not caught. The second call has catchError but is not subscribed to here, so it does not affect the first call's errors.
errorMessage after a 500 server error occurs?import { Component } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { catchError } from 'rxjs/operators'; import { throwError } from 'rxjs'; @Component({ selector: 'app-data', template: `<p>{{ errorMessage }}</p>` }) export class DataComponent { errorMessage = ''; constructor(private http: HttpClient) { this.http.get('/api/data').pipe( catchError(err => { this.errorMessage = 'Server error occurred'; return throwError(() => err); }) ).subscribe({ next: data => console.log(data), error: err => console.log('Error handled in subscribe') }); } }
The errorMessage is set inside the catchError operator before rethrowing the error. So after the HTTP error, errorMessage will contain 'Server error occurred'.
Option D is correct because catchError lets you handle errors before the observable reaches the subscriber, allowing recovery or transformation. Option D is wrong because errors can be handled earlier with catchError. Option D is false; retries require explicit operators. Option D is false; try-catch does not work with asynchronous observables.