HTTP Client & Interceptors

5 questions found

How do you make a basic GET request to a server using Angular's HttpClient?

Beginner
You inject the HttpClient service into your component or service, and call its get method with the target URL, which returns an observable that emits the response once the request completes successfully.
import { HttpClient } from '@angular/common/http';

constructor(private http: HttpClient) {}

getUsers() {
  return this.http.get<User[]>('/api/users');
}

// Elsewhere
this.userService.getUsers().subscribe((users) => console.log(users));
Real-world example A user list component fetches all users from a backend API using HttpClient's get method, subscribing to the resulting observable to display the data once it successfully arrives.

Common follow-ups: Why does HttpClient return an observable instead of a promise?;What happens if you forget to subscribe to the observable returned by a get request?

RxJS & Observables;Services & Dependency Injection

What is an HTTP interceptor in Angular, and what is it commonly used for?

Intermediate
An interceptor lets you intercept every outgoing HTTP request and incoming response, allowing you to modify them consistently in one central place, such as automatically adding an authentication token to every request's headers or logging every response for debugging.
import { HttpInterceptorFn } from '@angular/common/http';

export const authInterceptor: HttpInterceptorFn = (req, next) => {
  const authReq = req.clone({
    headers: req.headers.set('Authorization', `Bearer ${getToken()}`)
  });
  return next(authReq);
};
Real-world example An app automatically attaches the current user's authentication token to every single API request using one shared interceptor, instead of manually adding that header inside every single service method individually.

Common follow-ups: Why must the request object be cloned rather than modified directly inside an interceptor?;How would you register this interceptor so it applies to every HTTP request in the app?

Angular Security (XSS Sanitization & CSP);Services & Dependency Injection

How would you handle errors from an HTTP request in Angular, showing a friendly message to the user?

Intermediate
You use the catchError operator inside the observable's pipe, letting you catch any error the request throws, log it if needed, and return a fallback value or rethrow a more user friendly error that your component can display appropriately.
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';

getUsers() {
  return this.http.get<User[]>('/api/users').pipe(
    catchError((error) => {
      console.error('Failed to load users', error);
      return of([]); // fallback to an empty list instead of crashing
    })
  );
}
Real-world example A user list page shows an empty state message instead of a broken page when the backend API is temporarily unavailable, thanks to catchError providing a safe fallback value for the component to display.

Common follow-ups: What is the difference between handling an error with catchError versus in the subscribe method's error callback?;How would you show a specific error message based on the actual HTTP status code returned?

RxJS & Observables;Error Handling

How would you use an interceptor to automatically retry a failed HTTP request a few times before giving up?

Advanced
You combine an interceptor with RxJS's retry operator, which automatically resubscribes to a failed request a specified number of times, useful for handling brief, temporary network issues without requiring extra code in every single place that makes an HTTP call.
import { retry } from 'rxjs/operators';

export const retryInterceptor: HttpInterceptorFn = (req, next) => {
  return next(req).pipe(retry(2)); // retries up to 2 times on failure
};
Real-world example A mobile heavy app automatically retries any failed API request up to two times before showing an error, smoothing over brief network drops that are common on mobile connections, without needing extra retry logic in every service.

Common follow-ups: How would you add a delay between retry attempts instead of retrying immediately?;Should every type of request be retried, even ones that change data, like a payment submission?

RxJS & Observables;Error Handling

How do you send data to a server using a POST request with Angular's HttpClient?

Beginner
You call the post method on HttpClient, passing the target URL and the data you want to send as the request body, which Angular automatically converts to JSON by default, and it returns an observable just like a GET request does.
createUser(user: User) {
  return this.http.post<User>('/api/users', user);
}

// Elsewhere
this.userService.createUser(newUser).subscribe((created) => console.log('Created', created));
Real-world example A signup form sends the new user's details to the backend using a POST request through HttpClient, subscribing to the response to confirm the account was successfully created.

Common follow-ups: How would you set custom headers, like a content type, on a POST request?;What happens to the subscription if the component is destroyed before the request completes?

Forms;RxJS & Observables