Using Angular 2's HTTP Client to Interact with Servers


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 import & and inject it:


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

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

  getUser() {
    return this.http.get(`your api path`)
    .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. In home component, lets subscribe to that Observable and assign the data returned to the profilevariable in the component:


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

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

  selector: 'home-page',
  template: `profile.component.html`
export class HomeComponent {
  constructor(private userService: UserService) {}
  profile = {};

  loadUser() {
         data => {
            data => { this.profiles = Array.of(data.profile);  }, 
            error => {   } 


<div class="col-md-3" *ngFor="let profile of profiles" > 
     <div class="widget-style1">
          {{profile.username}} ({{}})    

Related Post

Latest Post

Recent Posts Widget

Make sure to never miss a thing...

Get the latest news from the creative industry along with other creative goodies, conveniently delivered to social media.