如何在AngularJS 2.0中发出HTTP请求

How to make HTTP requests in AngularJS 2.0

本文关键字:HTTP 请求 AngularJS      更新时间:2023-09-26

我只是想知道如何在新的angularjs 2.0中发出http请求,以及如何将此服务挂钩到控制器。

谢谢。

截至目前,http模块/组件仍在开发中,尚未发布。在此期间,有两种选择:

  • 获取(https://github.com/github/fetch)
  • axios (https://github.com/mzabriskie/axios)

你可以在这里了解更多关于新的http服务的信息:

  • https://github.com/jeffbcross/http-design
  • https://docs.google.com/document/d/1DMacL7iwjSMPP0ytZfugpU4v0PWUK0BT6lhyaVEmlBQ/edit

我认为已经添加了基本支持。基于这个例子:

  1. 用httpInjectables从'angular2/http'//index.ts引导你的应用

  2. 将Http注入构造函数constructor(Http: Http)//http_comps

  3. http.get('./people.json').map(res => res.json()).subscribe(people => this.people = people);

节选:

import {Component, View} from 'angular2/core';
import {Http, HTTP_BINDINGS} from 'angular2/http';
import {bootstrap} 'angular2/platform/browser';
import {CORE_DIRECTIVES,NgFor} from 'angular/common';
    @Component({
       selector: 'app'
    })
    @View({
        templateUrl: 'devices.html',
        directives: [CORE_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]);

下面是演示angular2 http特性的repo,这些特性可能会派上用场:

https://github.com/kaalpurush/ng2-http