Angular 4.3 introduce HTTP client module to request a call to HTTP request. We can define HTPP request in Services, services are user-defined classes used to access database and from server site and other activities. The front-end can’t make request directly to database because of security issue. Angular recommends only having template specific codes in components. A component’s responsibility is to enrich the UI/UX in the Angular application and delegate business logic to services. Components are consumers of services:
This new module is available in package @angular/common/http and a complete re-implementation of the former HttpModule. The new HttpClient service is included in HttpClientModule and can be used to initiate HTTP request and process responses within your application.
Application-specific or business logic such as persisting application data, logging errors, and file storage should be delegated to services, and components should consume the respective services to deal with the appropriate business or application-specific logic.
The httpClientModule is upgraded version of http from @angular/http module with the following improvements:
- Typed, synchronous response body access, including support for JSON body types
- JSON is an assumed default and no longer needs to be explicitly parsed
- Interceptors allow middleware logic to be inserted into the pipeline
- Immutable request/response objects
- Progress events for both request upload and response download
- Post-request verification & flush based testing framework
In this example we will learn
- How to use new HTTP Client Module
- The ngModel, bi direction data binding
Screen shot of our apps.
Step 1: Project Setup
We have to import our new Angular 4.3 HttpClient module
Step 2: Create a service to request HTTP request
We have to create a service class to request HTTP request to a remote server or site restcountries.eu to retrieve information about the a country. In our case we will create countries. http. service. this file in app/services folder. We have to create service folder and add the following code in app/services/countries.http.service.ts
Note : We have to import HttpClient from HttpClientModule and inject the HttpClient dependency in constructor.
Step 3: Modify the app.component.ts file
In app.component we will add input box and selection option to add or select the country from the countries list. Both input box and selection box are linked into single ngModel variable countryName in typescript file.
Add the following code in app.component.html file.