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:

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(`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:

app/profile.component.ts

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

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

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

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

app/profile.component.html

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



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.