HttpClient is designed to make HTTP requests easier and more powerful in Angular apps. It uses observables for async data, supports interceptors for modifying requests or responses, and handles JSON parsing automatically.
this.http.get('https://api.example.com/data').subscribe(data => console.log(data));
Subscribing to the observable returned by HttpClient triggers the HTTP request. When the response arrives, the callback logs the data.
HttpClient expects the body as a JavaScript object and automatically converts it to JSON and sets the correct headers. Passing a string or incorrect headers causes errors.
this.http.get('https://api.example.com/data').subscribe(data => console.log(data)); // No error handling provided
Without error handling, any HTTP error will not be caught inside subscribe, potentially causing unhandled errors in the app.
HttpClient returns observables. Unsubscribing from them cancels the HTTP request if it is still in progress.