AJAX Requests and Importing Modules in Angular Applications

Let's see how we can work with AJAX requests using "HttpClient" and add modules in an Angular application.

AJAX requests

Angular provides its own client for working with AJAX requests. In fact, it provides two such clients. The original one, Http, is deprecated. It had a solid core, but interacting with it was clunky and repetitive. The new tool, HttpClient brings several advantages.

HttpClient

First, it assumes that the response will be JSON, saving tedious time writing out for every request.

.map( response => response.json())

HttpInterceptors

It also accepts a generic type, further improving our editor’s awareness of what’s going on. Finally, it resurrects HttpInterceptors from AngularJS (unfamiliar with HttpInterceptors? You’ll find out later in this chapter). There’s a lot packed up in this little library, so let’s get started.

Importing modules

Since HttpClient is new to the Angular ecosystem, it’s not included by default. We need to explicitly import the module in the root app module (Angular modules represent a collection of components, services and other modules). Open app.module.ts and add the following lines:

Get hands-on with 1200+ tech skills courses.