45

我一直在玩Angular 2 Quickstart

如何在 Angular 2 中使用/导入 http 模块?

我看过Angular 2 Todo's.js,但它不使用 http 模块。

我之所以加入"ngHttp": "angular/http",dependencies因为package.json我听说 Angular 2 在某种程度上是模块化的。

4

13 回答 13

51

最后更新:2016 年 5 月 11 日
Angular 版本:2.0.0-rc.2
Typescript 版本:1.8.10

现场工作示例

一个如何将 Http 模块与 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));

于 2015-06-21T12:34:23.257 回答
25
  1. 我们正在开发一个单独的数据持久层,它将涵盖 HTTP。这还没有完成。
  2. 因为Zone在 Angular 2 中,您可以使用任何现有的机制来获取数据。这包括XMLHttpRequestfetch()任何其他第三方库。
  3. XHRincompiler是私有的,我们可以随时更改 API,因此不应使用。
于 2015-04-13T22:06:36.187 回答
21

在版本 37 中,您需要这样做:

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

并运行这个 tsd 命令:

tsd install angular2/http
于 2015-09-12T14:45:33.190 回答
8

在 Alpha 42 中大致相同,但可以注意到HeadersHTTP_PROVIDERS也来自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')
      );
  }

}

有关此内容以及如何使用此处返回的可观察对象的更多信息: https ://auth0.com/blog/2015/10/15/angular-2-series-part-3-using-http/

:)

于 2015-10-15T19:13:03.817 回答
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');
        })
    }
}

导致 404:
检测到
文件更改 检测到文件更改
GET /src/angular2/http 404 0.124 ms - 30

两件奇怪的事情:
1. /src/angular2/http - 不是可以找到 http 的路径,也不是我在代码中提供的路径。
2. core.js 位于 node_modules/angular2 文件夹中的 http.js 旁边,可以找到。

这有多奇怪?

更新 Mea culpa:没有一个例子提到你需要在你的html中引用http.js,比如
<script src="../node_modules/angular2/bundles/http.dev.js"></script>
......然后它就起作用了。
但是对于错误信息中的路径我还是没有解释。

于 2015-10-27T14:13:20.870 回答
6

除了下面给出的所有答案,如果我掩盖了一些额外的观点,这里是Http如何使用/导入所有内容......

ANGULAR2 HTTP(更新到 Beta !!)

首先,从名称中清楚我们必须像这样在 index.html 中导入 http 文件

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

或者您可以从此处通过 CDN 更新此内容

然后下一步我们必须从 angular 提供的包中导入Http和导入。HTTP_PROVIDERS

但是是的,在引导文件中提供 HTTP_PROVIDERS 是一个很好的做法,因为通过使用这种方式,它在全局级别提供并且可用于整个项目,如下所示。

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

进口来自....

import {http} from 'angular2/http';

使用 Http 使用 Rest API 或 json

现在,除了 http,我们还为 angular2/http 提供了更多选项,例如 Headers、Request、Requestoptions 等,这些选项主要在使用 Rest API 或临时 Json 数据时使用。首先,我们必须像下面这样导入所有这些:

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

有时我们需要在使用 API 发送 access_token 时提供 Headers 以及使用这种方式完成的更多事情:

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

现在来到 RequestMethods:基本上我们使用 GET、POST,但我们还有更多选项,您可以在此处参考...

我们可以通过使用使用请求方法RequestMethod.method_name

API 有更多选项,现在我通过使用一些重要方法发布了一个 POST 请求帮助示例:

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

欲了解更多信息,我在这里找到了两个最好的参考......这里......

于 2016-01-16T05:22:29.027 回答
4

我相信现在(alpha.35 和 36)需要是:

import {Http} from 'http/http';

请记住在您的 html 中添加(因为现在是一个单独的文件)引用:https ://code.angularjs.org/2.0.0-alpha.36/http.dev.js

于 2015-09-03T14:06:40.490 回答
2

赶紧跑:

npm install --save  @angular/http

然后通过导入

import {HttpModule} from '@angular/http'
于 2018-12-10T09:17:47.290 回答
2

跟进一些答案,这是使用该http模块的完整工作示例

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, []);
于 2015-11-17T22:57:25.037 回答
1

它已经在 angular2 中,所以你不需要在 package.json 中放任何东西

你只需要像这样导入和注入它。(这是一个带有仅记录响应的 methodThatUsesHttp() 的 Stuff 服务)

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);
        });
    }
}
于 2015-03-20T08:54:05.163 回答
1
import {Http, Response} from '@angular/http';
于 2016-08-07T21:55:53.143 回答
0

对于 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 {}

在你的服务类里面

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

您可能还需要的其他软件包

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

package.json

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

参考在这里

于 2018-01-04T02:27:05.203 回答
-1

一个使用 http 模块的简单示例:

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]);
于 2015-09-12T18:36:50.213 回答