Angular - HttpClient

The browsers support two different APIs for making HTTP requests:
1. XMLHttpRequest interface
2. fetch() API

Angular 4.3 introduced a new HttpClient service, which is a replacement for the Http service from Angular 2.

The HttpClient in @angular/common/http offers a simplified client HTTP API for Angular applications that rests on the XMLHttpRequest interface exposed by browsers. Additional benefits of HttpClient include testability features, typed request and response objects, request and response interception, Observable apis, and streamlined error handling.

Setup

Before you can use the HttpClient, you need to import the Angular HttpClientModule.

import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { HttpClientModule } from '@angular/common/http'; @NgModule({ imports: [ BrowserModule, HttpClientModule, ], declarations: [ AppComponent, ], bootstrap: [ AppComponent ] }) export class AppModule {}



Having imported HttpClientModule into the AppModule, you can inject the HttpClient into an application class as shown in the following ServiceClient example.


import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable() export class ServiceClient { constructor(private http: HttpClient) { } }


The ServiceClient fetches this file with a get() method on HttpClient.


srvUrl = 'srv/srv.json'; getConfig() { return this.http.get(this.srvUrl); }


1 comment:

  1. Casino | DrmCD
    Casino. DrmCD 공주 출장마사지 has over 30000 Slots available, a 충청북도 출장샵 unique 과천 출장샵 casino experience for 남양주 출장마사지 everyone! Play over 1000 Casino games, get your Signup Bonus,  Rating: 영천 출장안마 3.9 · ‎9 votes

    ReplyDelete