How to use/import http module?
Last update: May 11, 2016
Angular version: 2.0.0-rc.2
Typescript version: 1.8.10
Live working example.
A simple example of how to use the Http module with Observable:
import {bootstrap} from '@angular2/platform-browser-dynamic';
import {Component, enableProdMode, Injectable, OnInit} from '@angular/core';
import {Http, Headers, HTTP_PROVIDERS, URLSearchParams} from '@angular/http';
import 'rxjs/add/operator/map';
const API_KEY = '6c759d320ea37acf99ec363f678f73c0:14:74192489';
@Injectable()
class ArticleApi {
constructor(private http: Http) {}
seachArticle(query) {
const endpoint = 'http://api.nytimes.com/svc/search/v2/articlesearch.json';
const searchParams = new URLSearchParams()
searchParams.set('api-key', API_KEY);
searchParams.set('q', query);
return this.http
.get(endpoint, {search: searchParams})
.map(res => res.json().response.docs);
}
postExample(someData) {
const endpoint = 'https://your-endpoint';
const headers = new Headers({'Content-Type': 'application/json'});
return this.http
.post(endpoint, JSON.stringify(someData), { headers: headers })
.map(res => res.json());
}
}
@Component({
selector: 'app',
template: `<ul>
<li *ngFor="let article of articles | async"> {{article.headline.main}} </li>
</ul>`,
providers: [HTTP_PROVIDERS, ArticleApi],
})
class App implements OnInit {
constructor(private articleApi: ArticleApi) { }
ngOnInit() {
this.articles = this.articleApi.seachArticle('obama');
}
}
enableProdMode();
bootstrap(App)
.catch(err => console.error(err));
- We are working on a separate data persistence layer, that will cover HTTP. This is not finished yet.
- Because of
Zone
in Angular 2 you can use any existing mechanism for fetching data. This includesXMLHttpRequest
,fetch()
and any other third party libraries. -
XHR
in thecompiler
is meant to be private, and we can change the API at any time and as such should not be used.