Ang2

Using Angular 2's HTTP Client to Interact with Servers

Retrieve data from servers and use Observables (or Promises) to modify and/or return the result.

Eric Simons Up to date (Aug '17) Angular 2
PRO

Just like in Angular 1.x, Angular 2 also provides with its own service called Http for making requests to servers. Since providers should generally be registered at the top-most module and the Http 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 HttpModule from @angular/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, use observable to map & return the data

Just like in Angular 1.x, it's recommended that Http 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.

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

app/shared/user.service.ts

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';

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

  getUser() {
    return this.http.get(`https://conduit.productionready.io/api/profiles/eric`)
    .map((res:Response) => res.json());
  }

}

We need to import the map from rxjs in order to use the map operator. There's a few differences between $http from 1.x and Http in Angular 2. Http 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 Http is that Http doesn't actually make the request to the server until there is a subscription to the observable.

Although observables are the recommended way for dealing with data in Angular 2, you can convert them to promises by importing rxjs/add/operator/toPromise and then calling toPromise() on your observable. At first I found myself wanting to just use promises like the good ol' days of Angular 1, but I ended up finding that Observables are actually pretty great and not significantly different from how you'd write promise code anyways.

The getUser method is firing off a GET request to my profile info from the server. When the data comes back, we use the map operator to take the response data, convert it to JSON, and then reutrn it 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 2.

The Http service can also be configured using the RequestOptions class for setting other data for requests such as headers or query strings.

Additional Reading

Http Service API

Angular Server Communication Guide

RxJS Operators