I've been playing with Angular 2 Quickstart.
How can I use/import http module in Angular 2?
I've looked at Angular 2 Todo's.js, but it doesn't use the http module.
I've added "ngHttp": "angular/http",
to dependencies
in package.json
because I've heard Angular 2 is somewhat modular.
These are the steps in nutshell: First, import HttpClientModule from @angular/common/http . Next, open the main application module ( AppModule ) and add HttpClientModule in the imports array.
Generally, in node. js we can include or import a modules by using require directive with module name so to include HTTP module, we need to use require() function like as shown below.
Angular provides a client HTTP API for Angular applications, the HttpClient service class in @angular/common/http . The HTTP client service offers the following major features. The ability to request typed response objects. Streamlined error handling. Testability features.
An HTTP module is an assembly that is called on every request that is made to your application. HTTP modules are called as part of the ASP.NET request pipeline and have access to life-cycle events throughout the request. HTTP modules let you examine incoming and outgoing requests and take action based on the request.
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));
Zone
in Angular 2 you can use any existing mechanism for fetching data. This includes XMLHttpRequest
, fetch()
and any other third party libraries. XHR
in the compiler
is meant to be private, and we can change the API at any time and as such should not be used.In version 37 you need to do this:
///<reference path="typings/angular2/http.d.ts"/>
import {Http} from "angular2/http";
And run this tsd command:
tsd install angular2/http
Much the same in Alpha 42, but it can be noted that Headers
and HTTP_PROVIDERS
also come from angular2/http
.
import {Http, Headers, HTTP_PROVIDERS} from 'angular2/http';
export class App {
constructor(public http: Http) { }
getThing() {
this.http.get('http://example.com')
.map(res => res.text())
.subscribe(
data => this.thing = data,
err => this.logError(err),
() => console.log('Complete')
);
}
}
More on this and how to use observables that get returned over here: https://auth0.com/blog/2015/10/15/angular-2-series-part-3-using-http/
:)
import {Injectable} from 'angular2/core';
import {Http, HTTP_PROVIDERS} from 'angular2/http';
@Injectable()
export class GroupSelfService {
items:Array<any>;
constructor(http:Http){
http.get('http://127.0.0.1:8080/src/data/names.json')
.subscribe(res => {
this.items = res;
console.log('results found');
})
}
}
Results in a 404:
File change detected
File change detected
GET /src/angular2/http 404 0.124 ms - 30
Two strange things:
1. /src/angular2/http - is not the path where http can be found and not the path I've provided in the code.
2. core.js lies just beside http.js in the node_modules/angular2 folder and is found.
How strange is that?
Update
Mea culpa: None of the examples mentioned that you need to reference the http.js in your html like<script src="../node_modules/angular2/bundles/http.dev.js"></script>
...and then it worked.
But for the path in the error message I still have no explanation.
Apart from all answers given below if i cover up with some additional points Here is Http
how to use/import everything...
Firstly as clear from name we have to import http file in the index.html like this
<script src="node_modules/angular2/bundles/http.dev.js"></script>
or you can update this via CDN from here
then next step we have to import Http
and HTTP_PROVIDERS
from the bundles provided by angular.
but yes it is a good practice to provide HTTP_PROVIDERS in the bootstrap file because by using this way it provided on the global level and available for the whole project like following.
bootstrap(App, [
HTTP_PROVIDERS, some_more_dependency's
]);
and imports are from....
import {http} from 'angular2/http';
Consuming Rest API's or json using Http
Now along with the http we have some more options provided with the angular2/http i.e like Headers, Request, Requestoptions etc etc. which is mostly used while consuming Rest API's or temporary Json data. firstly we have to import all this like following:
import {Http, Response, RequestOptions, Headers, Request, RequestMethod} from 'angular2/http';
sometimes we need to provide Headers while consuming API's for sending access_token and many more things that is done using this way:
this.headers = new Headers();
this.headers.append("Content-Type", 'application/json');
this.headers.append("Authorization", 'Bearer ' + localStorage.getItem('id_token'));
now come to RequestMethods: bascially we use GET, POST but we have some more option you can refer here...
we can use use requestmethods by using RequestMethod.method_name
there are some more option for the API's for now i posted one example for POST request the help by using some important methods:
PostRequest(url,data) {
this.headers = new Headers();
this.headers.append("Content-Type", 'application/json');
this.headers.append("Authorization", 'Bearer ' + localStorage.getItem('id_token'))
this.requestoptions = new RequestOptions({
method: RequestMethod.Post,
url: url,
headers: this.headers,
body: JSON.stringify(data)
})
return this.http.request(new Request(this.requestoptions))
.map((res: Response) => {
if (res) {
return [{ status: res.status, json: res.json() }]
}
});
}
for more info i had found two best reference here.. and here...
I believe that now (alpha.35 and 36) is needed to be:
import {Http} from 'http/http';
Remember to add (since now is a separate file) the reference in your html: https://code.angularjs.org/2.0.0-alpha.36/http.dev.js
Following up on a few of the answers, here is a complete working example of using the http
module
index.html
<html>
<head>
<title>Angular 2 QuickStart</title>
<script src="../node_modules/es6-shim/es6-shim.js"></script>
<script src="../node_modules/systemjs/dist/system.src.js"></script>
<script src="../node_modules/angular2/bundles/angular2.dev.js"></script>
<script src="../node_modules/angular2/bundles/http.dev.js"></script>
<script>
System.config({
packages: {'app': {defaultExtension: 'js'}}
});
System.import('app/app');
</script>
</head>
<body>
<app>loading...</app>
</body>
</html>
app/app.ts
import {bootstrap, Component} from 'angular2/angular2';
import {Http, Headers, HTTP_PROVIDERS} from 'angular2/http';
@Component({
selector: 'app',
viewProviders: [HTTP_PROVIDERS],
template: `<button (click)="ajaxMe()">Make ajax</button>`
})
class AppComponent {
constructor(public http: Http) { }
ajaxMe() {
this.http.get('https://some-domain.com/api/json')
.map(res => res.json())
.subscribe(
data => this.testOutput = data,
err => console.log('foo'),
() => console.log('Got response from API', this.testOutput)
);
}
}
bootstrap(AppComponent, []);
Its already in angular2, so you dont need to put anything in package.json
You just have to import and inject it like this. (this is a Stuff service with a methodThatUsesHttp() that just logs the response)
import {XHR} from 'angular2/src/core/compiler/xhr/xhr';
export class Stuff {
$http;
constructor($http: XHR) {
this.$http = $http;
}
methodThatUsesHttp() {
var url = 'http://www.json-generator.com/api/json/get/cfgqzSXcVu?indent=2';
this.$http.get(url).then(function(res) {
console.log(res);
}, function(err) {
console.log(err);
});
}
}
import {Http, Response} from '@angular/http';
just run:
npm install --save @angular/http
and then import via
import {HttpModule} from '@angular/http'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With