Angular 2 HTTP Example

HTTP is one of the Protocols used to allow a browser to communicate with a server and vice versa.

angular 2 http
angular 2 http

 

example and resources from here: Compatible with Angular 2 final release

We will use HTTP Service (this service is part of Angular 2) to get Data from the server and show it in our <p> element.

If it’s your first time with Angular 2, Please check our hello world (step by step + npm and environment setup) tutorial here. to be able to run this example.

we will use observable in our example, if you want to read more about observable go from here: observable

Angular 2 Http Car Service
Angular 2 Http Car Service

 

Extract : from Angular 2 HTTP example.

Create our HttpCarService Class: http-example-service.component.ts

/**
 * Created by Tareq Boulakjar. from angulartypescript.com
 */
import {Injectable} from 'angular2/core';
import {Http, Response} from 'angular2/http';
import {Headers, RequestOptions} from 'angular2/http';
import {Observable}     from 'rxjs/Observable';

@Injectable()
export class HttpCarService {
    private _carsUrl:string = "http://localhost/angular-da-rest/angular2/products";
    constructor(private _http: Http){ }

    getCarsRestful(){
        return this._http.get(this._carsUrl).map(res => res.json());
    }
    postCarRestful(productCode:string,productName:string,productLine:string,buyPrice:number ){

        let body = JSON.stringify({ "productCode":productCode,"productName":productName,"productLine":productLine,"buyPrice":buyPrice });
        let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
        let options = new RequestOptions({ headers: headers, method: "post" });

        return this._http.post(this._carsUrl, body,options)
            .map(res => res.json())
            .catch(this.handleError);
    }
    private handleError (error: Response) {
        console.error(error);
        return Observable.throw(error.json().error || ' error');
    }
}

In this class we delegate the communication with the server.

In our Components later they will use this service to communicate with the server. It’s a good practice to delegate server side communications to a class (Service).

  • We include the Http service from angular2 : import {Http} from “angular2/http”;
  • We make our Class @Injectable to be able to call it as a service in our application.
  • We create a constructor with a private variable (_http instantiate the Angular HTTP service) .
  • We create two methods: getCarsRestful() and postCarRestful().
  • getCarsRestful() : we call this method to get data from the server (Restful API)
    • In angular 2 when we call a method like get/post with the HTTP Service the return is an observable (although we can use Promises if we want)
    • Once the result arrives from the server we call a map method to deal with Data.
    • The returned object observable is not useful directly we need to transform it to a JSON format using the .json()
    • The get method returns an observable of HTTP Responses. (not promise like in Angular 1.x)
    • We need to subscribe to this observable if we want to get Data. Until now we don’t have an observable of HTTP Responses (we are in sleep mode). This subscription allows us to get the response and catches errors in case of failure or if the method successes we can do some actions on our Data.

 

  • postCarRestful() : we call the post method with 3 parameters
    • The first parameter is the web service url.
    • Body: contains the JSON data to send to the server.
    • Options: contains additional header parameters
    • We call the map method to deal with the response.
    • In case the call fails we call the method handleError

 

html template
html template

Let’s create the HTML template of our Component.

This component will call our service created above.

 


<h2>Angular 2 HTTP Example – Typescript</h2>

<form
</div>

</div>


<div class="form-group">
<label class="col-xs-2 control-label" >Car Line :</label>

<div class="col-xs-10">
<input type="text" style="width: 300px" class="form-control" required [(ngModel)]="productLine">
</div>

</div>


<div class="form-group">
<label class="col-xs-2 control-label" >Car Price :</label>

<div class="col-xs-10">
<input type="text" style="width: 300px" class="form-control" required [(ngModel)]="buyPrice">
</div>

</div>


<div class="form-group">
<label class="col-xs-2 control-label text-primary" >Post Data :</label>

<div class="col-xs-10">
<button class="btn btn-success" (click)="postDataToServer()">Insert new Car : Restful API</button>


<strong>The result after Post</strong>: {{postMyCarToServer}}

</div>

</div>

</form>

call the service - inject it
call the service – inject it

Now let’s use our service. We create a component from where we will call our service:

angular-2-http-example-typescript.component.ts

 

/**
 * Created by Tareq Boulakjar. from angulartypescript.com
 */
import {Component} from 'angular2/core';
import {HttpCarService} from "./http-example-service.component";

// Our HTTP Component
@Component({
    selector: 'angular-2-http',
    templateUrl: 'app/angular-2-http-example-typescript.component.html',
    providers: [HttpCarService]

})
export class HttpExample {
    getMyCarsFromServer:string;
    postMyCarToServer:string;

    productCode:string;
    productName:string;
    productLine:string = "BMW 1 series";
    buyPrice:number;

    constructor(private _httpCarService:HttpCarService){

    }

    getDataFromServer (){
        this._httpCarService.getCarsRestful()
            .subscribe(
                data = > this.getMyCarsFromServer = JSON.stringify(data), // put the data returned from the server in our variable
                error = > console.log("Error HTTP GET Service"), // in case of failure show this message
                () = > console.log("Job Done Get !")//run this code in all cases
            );
    }
    postDataToServer (){
        this._httpCarService.postCarRestful(this.productCode,this.productName,this.productLine,this.buyPrice).subscribe(//call the post
                data = > this.postMyCarToServer = JSON.stringify(data), // put the data returned from the server in our variable
                error = > console.log("Error HTTP Post Service"), // in case of failure show this message
                () = > console.log("Job Done Post !")//run this code in all cases
            );
    }
}

 

  • In our Template we have a button to call the service and a paragraph (p) to show the result.
  • In our class we inject the service created above in the constructor.
  • Once injected we can call our method getCarsRestful() from our template after the button is clicked. Remember that getCarsRestful calls the get method and it returns and observable.
  • We need now to subscribe to observable. (subscription allow us to keep an eye on what happen in this observable)
  • After subscription we need to specify what to do in case of: success. (get the Data and put it in a variable, in our example we get the data as JSON and then to string )

 

bootstrap and


don’t forget !

HttpModule : module that holds all service providers needed in Angular 2 HTTP .

App modules file : app.module.ts

import { NgModule, ApplicationRef } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';
import { FormsModule } from '@angular/forms';

 

we create our main app: main.ts

 

....
import { AppModule } from './app/app.module';
....

This is the first example to illustrate how to use HTTP Service, in next tutorials we will show you new tips related to HTTP Service.

angular 2 http

example