Angular 2 is the latest framework for building web applications using typescript. Recently, angular team is skipped the version 3.x because, router package is shipped with 3.x previously, so instead of putting into 3.x, choose to move to 4.x.

Tuesday, 25 October 2016

Angular 2.0 HTTP Service


We will go through the http service in angular2

Http Get Sample :
import {Injectable} from '@angular/core';
import {Http, Response} from 'angular/http';
import {Observable} from 'rxjs/RX';
@Injectable()
export class TrainingService{
 constructor(private http:Http){
}

getProducts(){

return this.http.get('/api/products').map( (res:Response) => res.json()  ); } 
}

In the above example code, we used HttpModule from @angular/http library which holds a complete set of http services. 

Http Post Sample :

addProduct (body: object): Observable < >{ let data = JSON.stringify(body);
let headers  = new Header({'Content-Type':'application/json'});
let httpoptions = new RequestOptions({headers: headers});
return this.http.post(url, body, httpoptions)
                       .map((res.Response) => res.json())
                       .catch((error: any)  => Observable.throw(error.json().error));
}

 Observable.forkJoin() - run multiple concurrent http.get() requests

return Observable.forkJoin(
this.http.get('https://api/test.com/data.json').map((res:Response) => res.json()),
this.http.get('https://api/test.com/shops.json').map((res:Response) => res.json())
); 

Here is the full sample code which explains, how to get data from server and rendering into the template.

index.html 

<html>

  <head>
    <title> www.angular2.in Http sample code</title>

    <script src="zone.js"></script>
    <script src="Reflect.js"></script>
    <script src="system.src.js"></script>

    <script src="js/systemjs.config.js"></script>
    <script>
      System.import('myapp').catch(function(err){ console.error(err); });
    </script>

  </head>
  <body>
    <demo-app>Loading...</demo-app>
  </body>
</html>
 

boot.ts 

import {bootstrap} from '@angular/platform-browser-dynamic';
import {HTTP_PROVIDERS} from '@angular/http';
import {MyAppComponent} from './app.component'

import {MyCustomService} from './mycustom.service'

bootstrap(AppComponent, [
  HTTP_PROVIDERS,
  MyCustomService1
]);
 

app.component.ts

 
import {Component} from '@angular/core';
import {MyCustomService1} from './mycustom.service';
import {Observable} from 'rxjs/Rx';

@Component({
  selector: 'myapp',
  template:`
  <h1>http://angular2.in Demo</h1>
  <h2>Data</h2>
  <ul>
    <li *ngFor="let item of data"><input type="text" name="name" [(ngModel)]="item.name"></li>
  </ul> `
})
export class MyAppComponent {
  public data;
  public name;
  constructor(private _myCustomService: MyCustomService1) { }

  ngOnInit() {
    this.getData(); 
  }

  getData() {
    this._myCustomService.getData().subscribe(
       data => { this.data = data},
       err => console.error(err),
       () => console.log('done loading foods')
    );
  }

} 

mycustom.service.ts

import {Injectable} from '@angular/core';
import {HTTP_PROVIDERS, Http, Response, Headers, RequestOptions} from "@angular/http";
import {Observable} from 'rxjs/Rx';

@Injectable()
export class MyCustomService1 {

    constructor(private http:Http) {
    }
    getData() {
        return this.http.get('http://api.test.com/feeds.json').map((res:Response) => res.json());
    }
} 
 
 



 




0 coment�rios:

Post a Comment

Labels

Online Training

Your Name :
Your Email: (required)
Your Message: (required)

Powered by Blogger.

Recent Posts

Find Us On Facebook

Popular Posts