How to use / import http module?

I played with Angular 2 Quickstart .

How can I use / import the http module in Angular 2?

I looked at Angular 2 Todo's.js , but it does not use the http module.

I added "ngHttp": "angular/http", to the dependencies in package.json because I heard that Angular 2 is somewhat modular.

+41
Mar 07 '15 at 2:53
source share
13 answers

In version 37, you need to do the following:

 ///<reference path="typings/angular2/http.d.ts"/> import {Http} from "angular2/http"; 

And run this tsd command:

 tsd install angular2/http 
+19
Sep 12 '15 at 14:45
source

Last updated: May 11, 2016
Angular version: 2.0.0-rc.2
Typescript version: 1.8.10

Live working example .

A simple example of using 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)); 
+49
Jun 21 '15 at 12:34
source
  • We are working on a separate data retention layer that will cover HTTP. This is not over yet.
  • Because of Zone in Angular 2, you can use any existing mechanism to retrieve data. This includes XMLHttpRequest , fetch() and any other third-party libraries.
  • XHR in the compiler must be private, and we can change the API at any time and should not be used as such.
+25
Apr 13 '15 at 22:06
source

The same is true in Alpha 42, but you can see that Headers and HTTP_PROVIDERS also apply to 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 return here: https://auth0.com/blog/2015/10/15/angular-2-series-part-3-using-http/

:)

+8
Oct 15 '15 at 19:13
source
 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 404:
File change detected
File change detected
GET / src / angular2 / http 404 0.124 ms - 30

Two strange things:
1./src/angular2/http - not the path by which you can find http, not the path that I provided in the code.
2. core.js is located next to http.js in the node_modules / angular2 folder and is located.

How strange is that?

Mea culpa update : None of the examples mentioned that you need to reference http.js in your html, such as <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.

+6
Oct 27 '15 at 14:13
source

Besides all the answers below, if I hide behind some additional points Here is Http how to use / import everything ...

ANGULAR2 HTTP (UPDATED to Beta !!)

First, as the name implies, we must import the http file into index.html, like this

 <script src="node_modules/angular2/bundles/http.dev.js"></script> 

or you can update it via CDN from here

then in the next step we need to import Http and HTTP_PROVIDERS from the packages provided by angular.

but yes, it’s good practice to provide HTTP_PROVIDERS in the bootstrap file, because that way it is provided globally and is available to the entire project, as shown below.

 bootstrap(App, [ HTTP_PROVIDERS, some_more_dependency's ]); 

and import from ....

 import {http} from 'angular2/http'; 

Use Restover or json API with Http

Now, along with http, we have several more options provided with angular2 / http ie, for example, Headers, Request, Requestoptions, etc. etc. which is mainly used when using the Rest API or Json temporary data. Firstly, we must import it all as follows:

 import {Http, Response, RequestOptions, Headers, Request, RequestMethod} from 'angular2/http'; 

sometimes we need to provide headers, consuming the API to send access_token and much more, which is done as follows:

 this.headers = new Headers(); this.headers.append("Content-Type", 'application/json'); this.headers.append("Authorization", 'Bearer ' + localStorage.getItem('id_token')); 

now come to RequestMethods: basically we use GET, POST, but we have another option that you can here ...

we can use usage request methods using RequestMethod.method_name

There is another option for the API, now I posted one example of a POST request using several 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 information, I found the two best links here .. and here ...

+6
Jan 16 '16 at 5:22
source

I believe that now (alpha .35 and 36) it is necessary:

 import {Http} from 'http/http'; 

Do not forget to add (since now it is a separate file) a link in your html: https://code.angularjs.org/2.0.0-alpha.36/http.dev.js

+4
03 Sep '15 at 14:06
source

Following a few 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, []); 
+2
Nov 17 '15 at 22:57
source

Its already in angular2, so you don't need to put anything in package.json

You just need to import and enter it like this. (this is a Stuff service with a ThatUsesHttp () method that simply 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); }); } } 
+1
Mar 20 '15 at 8:54
source
 import {Http, Response} from '@angular/http'; 
+1
Aug 07 '16 at 21:55
source

just run:

 npm install --save @angular/http 

and then import through

 import {HttpModule} from '@angular/http' 
+1
Dec 10 '18 at 9:17
source

For angular 4.3 +, 5. +

 // app.module.ts: import {NgModule} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; // Import HttpClientModule from @angular/common/http import {HttpClientModule} from '@angular/common/http'; @NgModule({ imports: [ BrowserModule, // Include it under 'imports' in your application module // after BrowserModule. HttpClientModule, ], }) export class MyAppModule {} 

And inside your class of service

 import { HttpClient } from '@angular/common/http'; 

Other packages you may need

 import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse, HttpErrorResponse } from '@angular/common/http'; 

In package.json

 "@angular/http": "^5.1.2", 

Link here

0
Jan 04 '18 at 2:27
source

A simple example of using the http module:

 import {Component, View, bootstrap, bind, NgFor} from 'angular2/angular2'; import {Http, HTTP_BINDINGS} from 'angular2/http' @Component({ selector: 'app' }) @View({ templateUrl: 'devices.html', directives: [NgFor] }) export class App { devices: any; constructor(http: Http) { this.devices = []; http.get('./devices.json').toRx().subscribe(res => this.devices = res.json()); } } bootstrap(App,[HTTP_BINDINGS]); 
-one
Sep 12 '15 at 18:36
source



All Articles