← Back to index

Angular 2: How to use/import the http module?

Created: 2015-09-14 17:25  |  Source: http://stackoverflow.com/questions/28910864/angular-2-how-to-use-import-the-http

Ten. Million. Questions. Let's celebrate all we've done together.
Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

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

asked Mar 7 at 2:53
rilut

176111
    
Here is wrapper for making XHR calls from Angular 2 : github.com/arvindr21/ng2do-mean-app/blob/master/public/services/… You can go through the above code repo to see how it is consumed. –  Arvind Apr 29 at 13:06

6 Answers

up vote 2 down vote accepted

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

answered Sep 3 at 14:06
tomascharad

555513
    
I'm getting a cannot find module 'http/http' error in the typescript compiler when importing it, alpha 36 –  MonkeyBonkey Sep 5 at 12:27
    
@MonkeyBonkey you have to add the reference in your html: code.angularjs.org/2.0.0-alpha.36/http.dev.js –  tomascharad Sep 5 at 14:53
    
How would one do this using ES5 syntax? –  oravecz 21 hours ago
  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.
answered Apr 13 at 22:06
Misko Hevery

33.1k112934
3  
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 at 21:23
    
@BenjaminGruenbaum: Old post, but they are planning on using RxJS-Next. –  Jesse Good Aug 12 at 3:46

Last update: Jul 27, 2015

Angular version: 2.0.0-alpha.32

Typescript version: 1.5.3

A simple example of how to use the Http module with Observable:

app.ts:

import {Component, View, coreDirectives} from 'angular2/angular2';
import {QuestionApi} from '../data/questionApi';

@Component({
  selector: 'app',
  viewInjector: [QuestionApi]
})
@View({
  directives: [coreDirectives],
  template: `
  <div *ng-if="questions">
    {{questions | json}}
  </div>
  `
})

export class App {
  questions;

  constructor(public questionApi: QuestionApi) {
    questionApi.getQuestions().subscribe(res => this.questions = res);
    questionApi.getQuestionsFeed().subscribe(res => console.log(res));
    questionApi.createQuestion({'foo': 'bar'});
  }
}

questionApi.ts:

import {Injectable, bind} from 'angular2/di';
import {Http, Headers} from 'angular2/http';
import {Observable} from 'rx';
import * as io from 'socket.io-client';

@Injectable()
export class QuestionApi {
  constructor(public http: Http) {
  }

  // Get request and serialize the result to JSON
  getQuestions() {
    return this.http.get('http://localhost:3333/api/questions/')
      .toRx()
      .map(res => res.json());
  }

  // Post request with Headers
  createQuestion(question) {
    return this.http.post('http://localhost:3333/api/questions/',
      JSON.stringify(question),
      {
        headers: new Headers({
          'Content-Type': 'application/json'
        })
      })
      .toRx()
      .map(res => res.json());
  }

  // Create an Observable from event
  getQuestionsFeed() {
    var socket = io('http://localhost:3333');
    return Observable
      .fromEvent(socket, 'questions:feed')
      .map(res => JSON.parse(res));
  }
}

answered Jun 21 at 12:34
    
Incidentally you can just use http.get instead of http.request. :) –  Jean Jul 8 at 1:13

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);
        });
    }
}
answered Mar 20 at 8:54
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 at 8:59
    
Thanks, should've understood this sooner. –  rilut Mar 30 at 11:17

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
answered 2 days ago
Andreas

235417

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]);

You can have the complete working app here: https://github.com/kaalpurush/ng2-http

answered yesterday
Ariful Islam

22638
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? –  durron597 yesterday
    
Edited. Thanks. –  Ariful Islam yesterday

Your Answer

 

Sign up or log in

Sign up using Google

Sign up using Facebook

Sign up using Stack Exchange

Post as a guest

Name
Email

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.

asked

6 months ago

viewed

3626 times

active

yesterday

Hot Network Questions

Technology Life / Arts Culture / Recreation Science Other
  1. Stack Overflow
  2. Server Fault
  3. Super User
  4. Web Applications
  5. Ask Ubuntu
  6. Webmasters
  7. Game Development
  8. TeX - LaTeX
  1. Programmers
  2. Unix & Linux
  3. Ask Different (Apple)
  4. WordPress Development
  5. Geographic Information Systems
  6. Electrical Engineering
  7. Android Enthusiasts
  8. Information Security
  1. Database Administrators
  2. Drupal Answers
  3. SharePoint
  4. User Experience
  5. Mathematica
  6. Salesforce
  7. ExpressionEngine® Answers
  8. more (13)
  1. Photography
  2. Science Fiction & Fantasy
  3. Graphic Design
  4. Movies & TV
  5. Seasoned Advice (cooking)
  6. Home Improvement
  7. Personal Finance & Money
  8. Academia
  9. more (9)
  1. English Language & Usage
  2. Skeptics
  3. Mi Yodeya (Judaism)
  4. Travel
  5. Christianity
  6. Arqade (gaming)
  7. Bicycles
  8. Role-playing Games
  9. more (21)
  1. Mathematics
  2. Cross Validated (stats)
  3. Theoretical Computer Science
  4. Physics
  5. MathOverflow
  6. Chemistry
  7. Biology
  8. more (5)
  1. Stack Apps
  2. Meta Stack Exchange
  3. Area 51
  4. Stack Overflow Careers
site design / logo © 2015 Stack Exchange Inc; user contributions licensed under cc by-sa 3.0 with attribution required
rev 2015.9.14.2816