Loading
 
What's Next: View All Tutorial →

Angular Js 2 - Making a ajax call using the Http method and pipe async

In Angular Js 2, The ajax method will be called in the different way unlike jquery. The following are the step need to be do Step 1. Create a observable method   constructor(private http:Http) { } this.http.get('app/test.json...

Published Date: 10/12/2016  Last Modified Date: 10/12/2016    New Post




In Angular Js 2, The ajax method will be called in the different way unlike jquery.

The following are the step need to be do

Step 1. Create a observable method

 
constructor(private http:Http) { }
this.http.get('app/test.json')    //It retuns the Observerbale object. 
The Observabale is responsible for sending a request and getting the response.

Step 2. Application need to subscribe for the Observerable event to get the response

 
this.http.get('app/test.json')
.subscribe(
        data => {
          console.log("data"+JSON.stringify(data));   //on success     -- this is success block      
        },
        error => {
          console.log("error"+error);   //on error - This is error block         
        }
      );
. subscribe() is used to subscribe to the Observable event

data==> console.log(data);  is same as data==> { console.log(data);  }  , we need to add curly brace if we want to execute multiple line



 

Step 3. Alter the response object using map


We can use the map object if we want to alter the response object. 

Usually the response object will contain all the status code, response text and other details, if we want to extract ony the json object and return to subscribe method, we can add map method

 
this.http.get('app/test.json')
.map((data: Response) => data.json())
.subscribe(
        data =>     console.log("data"+JSON.stringify(data))        
        error =>    console.log("error"+error)     
      );

.map((data: Response) => data.json())  - this return only the json data in the response object
 

Step 4: Map method Error Handler

 
 .map((data: Response) => data.json())
 .catch(this.handleError);
 

Step 5: Binding response data to the Html page


We can store the resposne object in the class level variable of the component class, the Angular js update the value in the html automatically if the class level variable is mapped to the template html.

 
export class AppComponent{
items : any[] = [];
}
.subscribe(
        data => {
          for (let key in data) {
            myArray.push(data[key]);
          }
          this.items = myArray;        //class level variable items is updated here, the template refering items variable automatically updated. No need to use like .innerHtml('') or $().html()
        }
      );
template: `
<ul>
  <li *ngFor="let item of items">{{item}}</li>
</ul>
`
 

Step 6: The obeservable object can be accessed using async pipe also


The obeservable object can be accessed using async pipe also
 
template: '{{this.http.get('app/test.json') | async | json}}'

| async -  async pipe invoke rest call and print json object

| json - json pipe print the json object as string

 

Code Snippet


This example show you how to execute GET, POST and async pipe method.



Filename: app/http.service.ts
 
import { Injectable } from '@angular/core';
import { Http, Response, Headers } from "@angular/http";
import 'rxjs/Rx';
import { Observable } from "rxjs/Rx";

@Injectable()
export class HttpService {

  constructor(private http: Http) {
  }

  getData() {
    return this.http.get('app/test.json')
      .map((response: Response) => response.json());
  }

  sendData(location : string,timestamp : string) {
  
    const requestbody = null;
    const headers = new Headers();
    //   headers.append('Content-Type', 'application/json');
 
    //headers.append('Content-Type', 'application/x-www-form-urlencoded');
 
    let urlSearchParams = new URLSearchParams();
    urlSearchParams.append('location', location);
    urlSearchParams.append('timestamp', timestamp);
    let params = urlSearchParams.toString()
        
    return this.http.post('https://maps.googleapis.com/maps/api/timezone/json?'+params, requestbody, 
    {
      headers: headers
    })
      .map((data: Response) => data.json())
      .catch(this.handleError);
  }

  getOwnData() {
    return this.http.get('app/test.json')
      .map((response: Response) => response.json());
  }

  private handleError (error: any) {
    console.log(error);
    return Observable.throw(error.json());
  }
}

Things to know:

@Injectable() - for Dependency injection, Once created, the same class can be used anywhere. This increase the resuability.


import 'rxjs/Rx'; and import {Observable } from 'rxjs/Rx' need to be imported for Observables



Filename:  app.appComponent.js 
 
import { Component } from '@angular/core';

import { HttpService } from "./http.service";

@Component({
  selector: 'my-app',
  template: `
  
Example1 : Get data from REST API<br>

<button (click)="onGetData()">Get Data</button>
<ul>
  <li *ngFor="let item of items">{{item}}</li>
</ul>
<hr>

Example 2: Post data to Rest API and print the result <br>
<button (click)="onPostData('39.6034810,-119.6822510','1331161200')">Post Data</button>


<div *ngIf="postjsonresponserecevied">
Response: {{postjsonresponse}}
</div>

<hr>

Example 3: Invoke Ajax call via pipe async <br>
<p>{{asyncString | async | json}}</p>
`
})
export class AppComponent { 
  
  items: any[] = [];
  asyncString = this.httpService.getData();
  postjsonResponse : string = "empty response";
  postjsonresponserecevied : boolean =false;

  constructor(private httpService: HttpService) {}

  onPostData(location: string, timestamp: string) {
    this.httpService.sendData( location,  timestamp)
      .subscribe(
        data => {
          console.log("data"+JSON.stringify(data));
          this.postjsonresponserecevied = true;
          this.postjsonresponse = JSON.stringify(data);
        },
        error => {
          console.log("error"+error);
          this.postjsonresponserecevied = true;
          this.postjsonResponse = error;
        }
      );
  }

  onGetData() {
    this.httpService.getOwnData()
      .subscribe(
        data => {
          console.log(data);
          data= data.stateList;
          const myArray = [];
          for (let key in data) {
            myArray.push(data[key]);
          }
          this.items = myArray;
          console.log(this.items);
        }
      );
  }
  
}


Things to know

import { HttpService } from "./http.service"  the injectable service need to important to refer the http service , It increase the resuability.


app/test.json
 
{
"stateList": [
  "Tamil Nadu",
  "Kerala"
  ]
}


app/app.module.ts
 
import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent }  from './app.component';
import { HttpModule } from "@angular/http";


import { HttpService } from "./http.service";

@NgModule({
  imports:      [ BrowserModule , HttpModule],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ],
  providers: [HttpService]
})
export class AppModule { }

Things to Know:

HttpModule - Need to added in imports

HttpService - need to be added in the providers as it is @Injectible() class - 


 

Program Output:


Example1 : Get data from REST API
Get Data
  • Tamil Nadu
  • Kerala

Example 2: Post data to Rest API and print the result 
Post Data
Response: {"dstOffset":0,"rawOffset":-28800,"status":"OK","timeZoneId":"America/Los_Angeles","timeZoneName":"Pacific Standard Time"}

Example 3: Invke Ajax call via pipe async 

{ "stateList": [ "Tamil Nadu", "Kerala" ] }



A live sampe program is available here, Click here to lauch

https://plnkr.co/edit/tWLInNMFqjlOEumpuOMu?p=preview
Awaiting for Administrator approval





Tags: Http Pipe

← Back to list


Related Post




×