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

ril*_*lut 42 angular2-http angular

我一直在玩Angular 2 Quickstart.如何在Angular 2中使用/导入http模块?
我看过Angular 2 Todo的.js,但它没有使用http模块.

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

Ita*_*zki 50

最后更新: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));
Run Code Online (Sandbox Code Playgroud)


Mis*_*ery 25

  1. 我们正在开发一个单独的数据持久层,它将覆盖HTTP.这还没有完成.
  2. 由于Zone在Angular 2中,您可以使用任何现有机制来获取数据.这包括XMLHttpRequest,fetch()以及任何其他第三方库.
  3. XHR在本compiler应是私有的,我们可以随时更改API,因此不应使用.

  • 我之前在其他(可能更合适的)论坛中表达过它 - 但是我想指出我不确定为什么选择在Http模块中使用Rx observable.特别是因为他们的API与ECMAScript的后续类型有很大的不同,它与下一个版本不同(RxJS目前正被重写为不同的API),就像你说的那样_can_使用`fetch`无论如何.这是一个已经被弃用和非标准的API投注它不适合的东西(根据它的发明者) - 但哦,好吧,我猜你已经有了你的理由. (4认同)

And*_*eas 19

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

///<reference path="typings/angular2/http.d.ts"/>    
import {Http} from "angular2/http";
Run Code Online (Sandbox Code Playgroud)

并运行此tsd命令:

tsd install angular2/http
Run Code Online (Sandbox Code Playgroud)

  • 我没有在演示中看到[任何引用](https://github.com/johnpapa/angular2-tour-of-heroes/search?utf8=%E2%9C%93&q=http)到`angular2/http` @GabrielGuerrero (3认同)
  • 不再需要///引用,tsc自1.6.2以来,期望在node_modules中找到angular/http.js,并且它旁边应该是一个angular/http.d.ts这应该成为标准的IDE,IDE这个作品现在是最新的VS代码,WebStorm的早期访问,还有一个用于崇高文本的微软插件,你可以在angular.io的最新教程中看到这个 (2认同)

cie*_*nki 8

许多在阿尔法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')
      );
  }

}
Run Code Online (Sandbox Code Playgroud)

有关这方面的更多信息以及如何使用在此处返回的observable:https: //auth0.com/blog/2015/10/15/angular-2-series-part-3-using-http/

:)


Tho*_*ers 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');
        })
    }
}
Run Code Online (Sandbox Code Playgroud)

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>
......然后它就有用了.
但对于错误消息中的路径,我仍然没有解释.


Par*_*ain 6

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

ANGULAR2 HTTP(更新到Beta !!)

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

<script src="node_modules/angular2/bundles/http.dev.js"></script>
Run Code Online (Sandbox Code Playgroud)

或者你可以从这里通过CDN更新

然后下一步我们必须导入HttpHTTP_PROVIDERS从由角提供的捆绑包.

但是,在bootstrap文件中提供HTTP_PROVIDERS是一个好习惯,因为通过这种方式,它在全局级别提供并可用于整个项目,如下所示.

bootstrap(App, [
    HTTP_PROVIDERS, some_more_dependency's
]);
Run Code Online (Sandbox Code Playgroud)

和进口来自......

import {http} from 'angular2/http';
Run Code Online (Sandbox Code Playgroud)

使用Http消耗Rest API或json

现在连同http我们还提供了更多的angular2/http选项,例如Headers,Request,Requestoptions等,它们主要在使用Rest API或临时Json数据时使用.首先,我们必须导入以下所有这些:

import {Http, Response, RequestOptions, Headers, Request, RequestMethod} from 'angular2/http';
Run Code Online (Sandbox Code Playgroud)

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

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

现在来到RequestMethods:基本上我们使用GET,POST但我们还有一些你可以参考的选项......

我们可以使用使用requestmethods 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() }]
                }
            });
    }
Run Code Online (Sandbox Code Playgroud)

更多的信息我已经找到了最好的两个参考这里..在这里...