44

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.

Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129
luthfianto
  • 1,746
  • 3
  • 22
  • 37
  • 1
    Here is wrapper for making XHR calls from Angular 2 : https://github.com/arvindr21/ng2do-mean-app/blob/master/public/services/xhr-factory.es6 You can go through the above code repo to see how it is consumed. – Arvind Apr 29 '15 at 13:06

13 Answers13

51

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));
Itay Radotzki
  • 857
  • 1
  • 8
  • 11
25
  1. We are working on a separate data persistence layer, that will cover HTTP. This is not finished yet.
  2. Because of Zone in Angular 2 you can use any existing mechanism for fetching data. This includes XMLHttpRequest, fetch() and any other third party libraries.
  3. 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.
Misko Hevery
  • 47,936
  • 11
  • 40
  • 36
  • 4
    I've expressed it before in other (and probably more appropriate) forums before - but I want to point out that I'm not sure why the choice was made to use Rx observables in the Http module. Especially since their API is different from ECMAScript's following type considerably, it's different from its next version (RxJS is currently being rewritten to a different API) and like you've said you _can_ use `fetch` anyway. This is betting on an already deprecated and nonstandard API for something it doesn't fit well in (according to its inventor) - but oh well, I guess you've had your reasons. – Benjamin Gruenbaum Jul 12 '15 at 21:23
  • @BenjaminGruenbaum: Old post, but they are planning on using [RxJS-Next](https://github.com/angular/angular/issues/3110). – Jesse Good Aug 12 '15 at 03:46
  • @Misko What is the best way to find the percentage of completion when using Angular2 Http service? – siva636 Aug 02 '16 at 16:58
20

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
Andreas
  • 675
  • 9
  • 18
  • 2
    the ///reference is no longer needed, tsc since 1.6.2 , expects to find angular/http.js inside node_modules and next to it should be a angular/http.d.ts this is suppose to become sort of standard, IDE were this works now are latest VS code , the Early Access of WebStorm, and there is a microsoft plugin for sublime text you can see this working in the latest tutorial in the angular.io – Gabriel Guerrero Oct 21 '15 at 21:04
  • Github of the angular heroes tutorial where it can be seen working https://github.com/johnpapa/angular2-tour-of-heroes/ – Gabriel Guerrero Oct 21 '15 at 21:12
  • 3
    I don't see [any references](https://github.com/johnpapa/angular2-tour-of-heroes/search?utf8=%E2%9C%93&q=http) to `angular2/http` in the demo anymore @GabrielGuerrero – 0xcaff Dec 18 '15 at 02:53
8

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/

:)

cienki
  • 1,639
  • 1
  • 16
  • 14
6
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.

  • This is exactly what's happening to me - I think the weird GET is due to require just firing a request at ./anguar/http. Anyway your suggestion of including http.dev.js worked a treat – stringy05 Nov 26 '15 at 03:05
6

Apart from all answers given below if i cover up with some additional points Here is Http how to use/import everything...

ANGULAR2 HTTP (UPDATED to Beta !!)

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...

Community
  • 1
  • 1
Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215
4

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

tomascharad
  • 3,156
  • 23
  • 24
2

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, []);
jczaplew
  • 1,715
  • 1
  • 17
  • 21
1

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);
        });
    }
}
  • 1
    however it doesn't work exactly like $http in angular 1.x... you have to manually parse the response according to type... `this.$http.get(url).then((res) => { console.log(JSON.parse(res)); }, (err) => { console.log(err); });` – Filip Bech-Larsen Mar 20 '15 at 08:59
1
import {Http, Response} from '@angular/http';
Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215
previousdeveloper
  • 315
  • 2
  • 6
  • 12
1

just run:

npm install --save  @angular/http

and then import via

import {HttpModule} from '@angular/http'
Bsquare ℬℬ
  • 4,423
  • 11
  • 24
  • 44
Ratnabh kumar rai
  • 1,426
  • 4
  • 21
  • 48
  • `import {HttpModule} from '@angular/http'`: true. `npm install --save @angular/http`: not necessary. "@angular/http" should already be available when the Angular project is created. – paulsm4 Feb 20 '19 at 20:24
0

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 service class

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

Other packages you might also need

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

In package.json

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

Reference is here

Frank Nguyen
  • 6,493
  • 3
  • 38
  • 37
-1

A simple example 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]);
Ariful Islam
  • 970
  • 8
  • 16
  • 1
    Please don't post link-only answers to your own site. Instead, put the essential information in your answer itself. See: [**What signifies “Good” self promotion?**](http://meta.stackexchange.com/q/182212/200235) – durron597 Sep 12 '15 at 20:16