How to use/import http module?

爱⌒轻易说出口 提交于 2019-11-26 20:19:59

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

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

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

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

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);
        });
    }
}
previousdeveloper
import {Http, Response} from '@angular/http';
Ratnabh kumar rai

just run:

npm install --save  @angular/http

and then import via

import {HttpModule} from '@angular/http'

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

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]);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!