concept HttpClient in category angular

appears as: HttpClient, HttpClient
Angular Development with Typescript, Second Edition

This is an excerpt from Manning's book Angular Development with Typescript, Second Edition.

Components are the centerpiece of the Angular architecture. Figure 1.2 shows a high-level diagram of a sample Angular application that consists of four components and two services, all packaged inside a module. Angular injects its HttpClient service into your app’s Service1, which in turn is injected into the GrandChild1 component.

Listing 5.5. Injecting HttpClient into ProductService
import {HttpClient} from '@angular/common/http';
import {Injectable} from "@angular/core";

@Injectable()
export class ProductService {
    constructor(private http: HttpClient) {                   #1
       let products = http.get<string>('products.json')       #2
                     .subscribe(...);                         #3
     }

Angular applications can communicate with any web server supporting HTTP, regardless of what server-side platform is used. In this chapter, we’ll show you how to use the HttpClient service offered by Angular. You’ll see how to make HTTP GET and POST methods with HttpClient. And you’ll learn how to intercept HTTP requests to implement cross-cutting concerns, such as global error handling.

This chapter starts with a brief overview of Angular’s HttpClient service, and then you’ll create a web server using the Node.js and Express.js frameworks. The server will serve the data required for most code samples in this chapter.

12.4.5. Injecting HttpClient into a service

Angular offers an easy way for separating the business logic implementation from rendering the UI. Business logic should be implemented in services, and the UI in components, and you usually implement all HTTP communications in one or more services that are injected into components. For example, your ngAuction app that comes with chapter 11 has the ProductService class with the injected HttpClient service. You inject a service into another service.

ProductService reads the products.json file using HttpClient, but it could get the product data from a remote server the same way you did in the previous section. ProductService is injected into components of ngAuction. Check the source code of ProductService and CategoriesComponent in ngAuction that comes with chapter 11, and you’ll recognize the pattern shown in figure 12.10.