Angular

Using Angular's HTTP Client to Interact with Servers

PRO

Just like in AngularJS, Angular provides us with its own service called HttpClient for making requests to servers. Since providers should generally be registered at the top-most module and the HttpClient service is usually used in many places throughout the app, it's acceptable to register it either in the root AppModule or the SharedModule of your application when it gets bootstrapped. We can do this by importing HttpClientModule from @angular/common/http, which contains all the providers we'll need for our application to make requests. In this example, we'll create a service to fetch a profile from the RealWorld API.

Making our first HTTP request

Make request to an API that returns an observable. Then, subscribe to the returned observable to use the results in your application.

Just like in AngularJS, it's recommended that HttpClient calls are wrapped within services instead of being used in Components directly. This allows for greater flexibility for your application structure as you can reuse your your calls throughout the app, as well the ability to implement more advanced features such as caching.

Advanced features can also be enabled using Http Interceptors.

HTTP Interception is a major feature of @angular/common/http. With interception, you declare interceptors that inspect and transform HTTP requests from your application to the server. The same interceptors may also inspect and transform the server's responses on their way back to the application. Multiple interceptors form a forward-and-backward chain of request/response handlers.

To use the HttpClient service we need to (you guessed it) import & and inject it:

app/shared/user.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpResponse } from '@angular/common/http';

@Injectable()
export class UserService {
  constructor (
    private http: HttpClient
  ) {}

  getUser() {
    return this.http.get(`https://conduit.productionready.io/api/profiles/eric`);
  }

}

There are a few differences between $http from AngularJS and HttpClient in Angular. HttpClient returns an Observable with the Response object, versus $http which returns Promises. The major difference between Promises and Observables is that Observables may emit data more than once, which is why they can be subscribed to and unsubscribed from. The other major difference between $http and HttpClient is that HttpClient doesn't actually make the request to the server until there is a subscription to the observable.

The getUser method is firing off a GET request to my profile info from the server. When the data comes back, the data is returned to any subscribers that are waiting for the data to resolve.

In home component, lets subscribe to that Observable and assign the data returned to the profile variable in the component:

app/profile.component.ts

import { Component } from '@angular/core';

import { UserService } from './shared/index';

@Component({
  selector: 'home-page',
  template: `
  <div>
    <button (click)="loadUser()">Load profile</button>
    {{ profile | json }}
  </div>
  `
})
export class HomeComponent {
  constructor(private userService: UserService) {}
  profile = {};

  loadUser() {
    this.userService.getUser().subscribe(data => this.profile = data);
  }
}

You can view the working example here:

And now when you click the button, you see the profile data come back and get displayed on the page! That's the basics of making http requests in Angular.

The HttpClient service can also be configured using the Options and HttpParams for setting other data for requests such as headers or query strings.

Additional Reading

HttpClient Service API

Angular Server Communication Guide

RxJS Operators

 

I finished! On to the next tutorial