Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use/import http module?

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.

like image 892
luthfianto Avatar asked Mar 07 '15 02:03

luthfianto


People also ask

How do I add an HttpClient module?

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.

Which function will import HTTP module in application?

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.

What is HTTP module in angular?

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.

What is HTTP module?

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.


11 Answers

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));
like image 98
Itay Radotzki Avatar answered Oct 02 '22 21:10

Itay Radotzki


  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.
like image 25
Misko Hevery Avatar answered Oct 02 '22 22:10

Misko Hevery


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
like image 34
Andreas Avatar answered Oct 02 '22 21:10

Andreas


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/

:)

like image 22
cienki Avatar answered Oct 02 '22 20:10

cienki


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.

like image 39
Thomas Bücklers Avatar answered Oct 02 '22 22:10

Thomas Bücklers


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

like image 43
Pardeep Jain Avatar answered Oct 02 '22 21:10

Pardeep Jain


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

like image 32
tomascharad Avatar answered Oct 02 '22 22:10

tomascharad


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, []);
like image 34
jczaplew Avatar answered Oct 02 '22 20:10

jczaplew


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);
        });
    }
}
like image 26
Filip Bech-Larsen Avatar answered Oct 02 '22 20:10

Filip Bech-Larsen


import {Http, Response} from '@angular/http';
like image 34
previousdeveloper Avatar answered Oct 02 '22 22:10

previousdeveloper


just run:

npm install --save  @angular/http

and then import via

import {HttpModule} from '@angular/http'
like image 26
Ratnabh kumar rai Avatar answered Oct 02 '22 22:10

Ratnabh kumar rai