Angular 2 Http
Http
Angular 2 prepares http module same as Angular 1
To use
import Http
import { Http } from '@angular/http';
API details are Http – ts
Example(GET)
Prepare json file to test GET request
project |- data |- data.json
data.json
{ "id": 1, "name": "Taro" }
import { Component } from '@angular/core'; import { Http } from '@angular/http'; @Component({ selector: 'app', template: `<div id="test" (click)="getData()">Json Data : {{body}} </div>` }) export class HttpTestComponent { constructor(private http: Http){ this.body = ""; } private body : string; private getData(): void { this.http.request('/data/data.json').subscribe(response => this.body = response.text()); // Same //this.http.get('/data/data.json').subscribe(response => this.body = response.text()); } }
Get data as string. In this example, click div and show json data as text.
subscribe receive data
Convert object
To use map operation, we can convert json data
map is rsjx Observable operation.
data.ts
export class Data { id: number; name: string; }
httptest.ts
import { Component } from '@angular/core'; import { Http } from '@angular/http'; import 'rxjs/add/operator/map'; import { Data } from './data'; @Component({ selector: 'app', template: `<div id="test" (click)="getData()">Data :{{data.id}} </div>` }) export class HttpTestComponent { constructor(private http: Http){ this.data = new Data(); } private data: Data; private getData(): void { // O.K. json -> object this.http.get('/data/data.json').map(res => res.json()).subscribe(json => this.data = json, err => console.log(err)); } }
map and subscribe.
Convert json data to Typescript object.
Receive json array and display
Next is json array.
Prepare one more data.
This is json array
multi.json
[ {"id": 1, "name": "Taro"}, { "id": 2, "name": "Jiro" } ]
httptest.ts
import { Component } from '@angular/core'; import { Http } from '@angular/http'; import 'rxjs/add/operator/map'; import { Data } from './data'; @Component({ selector: 'app', template: ` <div id="test" (click)="getMulti()">Multidata : <ul> <li *ngFor="let tmp of array"> {{tmp.id}} : {{tmp.name}} </li> </ul> </div>` }) export class HttpTestComponent { constructor(private http: Http){ this.array = new Array(); } private array: Date[]; private getMulti(): void { this.http.get('/data/multi.json').map(res => res.json()).subscribe(json => this.array = json); } }
Post
Under construction