如何use/importhttp模块?

How to use/import http module?

我一直在玩Angular 2 Quickstart

如何在 Angular 2 中 use/import http 模块?

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

我在 package.json 中将 "ngHttp": "angular/http", 添加到 dependencies 因为我听说 Angular 2 有点模块化。

它已经在angular2中了,所以你不需要在package.json

中放任何东西

你只需要像这样导入和注入它。 (这是一个 Stuff 服务,其方法 ThatUsesHttp() 仅记录响应)

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. 我们正在开发一个单独的数据持久层,它将涵盖 HTTP。这还没完。
  2. 由于 Angular 2 中的 Zone,您可以使用任何现有机制来获取数据。这包括 XMLHttpRequestfetch() 和任何其他第三方库。
  3. compiler中的
  4. XHR是私有的,我们可以随时更改API,因此不应使用。

最后更新时间:2016 年 5 月 11 日
Angular版本:2.0.0-rc.2
打字稿版本:1.8.10

Live working example.

如何将 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));

我认为现在(alpha.35 和 36)需要:

import {Http} from 'http/http';

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

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

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

并且运行这个tsd命令:

tsd install angular2/http

一个使用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]);

在 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/

:)

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:
检测到文件更改
检测到文件更改
获取 /src/angular2/http 404 0.124 毫秒 - 30

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

这有多奇怪?

更新 Mea culpa:None 的示例中提到您需要在 html 中引用 http.js,例如
<script src="../node_modules/angular2/bundles/http.dev.js"></script>
...然后就成功了。
但是对于报错信息中的路径我还是没有解释。

根据一些答案,这里是使用 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, []);

除了下面给出的所有答案之外,如果我掩盖了一些额外的要点,这里是 Http 如何 use/import 一切...

ANGULAR2 HTTP(已更新为测试版!!)

首先从名字上看我们必须像这样在 index.html 中导入 http 文件

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

or you can update this via CDN from here

然后下一步我们必须从 angular.

提供的包中导入 HttpHTTP_PROVIDERS

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

进口来自....

import {http} from 'angular2/http';

Consuming Rest API's or json using Http

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

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

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

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

现在来到 RequestMethods:基本上我们使用 GET,POST 但我们有更多选择,您可以 refer here...

我们可以通过使用 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() }]
                }
            });
    }

有关更多信息,我找到了两个最佳参考 here.. and here...

import {Http, Response} from '@angular/http';

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

在你的服务里面class

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

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

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

package.json

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

参考是here

只是 运行:

npm install --save  @angular/http

然后通过

导入
import {HttpModule} from '@angular/http'