权威教程 – 笔记06 – Angular HTTP库

1 简介

Angular有自己的http库。
我们不希望页面在http请求从外部服务器返回前一直失去响应。因此,我们的http请求是异步的。

在JavaScript中,通常有3种处理异步代码的方式
 1) 回调 (callback)
 2) 承诺 (promise)
   async函数返回的是一个Promise对象
 3) 可观察对象 (observable)

在Angular中,处理异步代码最佳方式就是使用 => 可观察对象

2 @angular/http

http在Angular中被拆分为一个单独的模块。
这意味着需要从@angular/http中导入一些常量。
@angular/http非常灵活并且广泛适用于各种API
@angular/http的一个强大特性就是个支持模拟后台。这一点在测试中非常有用。

API:
 GET    this.http.request().subscribe()  url
 POST   this.http.post().subscribe()     url,请求体
 PUT    this.http.put().subscribe()      url,请求体
 PATCH  this.http.patch().subscribe()    url,请求体
 DELETE this.http.delete().subscribe()   url
 HEAD   this.http.head().subscribe()     url

subscribe接收三个参数: onSuccess, onError, onCompletion

RequestOptions
  method
  headers
  body
  mode
  credentials
  cache
  url
  search
import { Http, Response, RequestOptions, Headers } from '@angular/http';

/*
 把HttpModule作为依赖项,加入NgModule的imports列表之中。
 这样就可以把Http(和另外一些模块)导入组件之中
*/
import { HttpModule } from '@angular/http';

3 SimpleHTTPComponent

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

@Component({
  selector: 'simple-http',
  template:`
    <h2>Basic Request</h2>
    <button type="button" (click)="makeRequest()">Make Request</button>
    <div *ngIf="loading">loading...</div>
    <pre>{{ data | json }}</pre>
  `
})
export class SimpleHTTPComponent {
    data: Object; // 默认为 public属性
    loading: boolean; // 载入指示器

    /*
      等同于
     http: Http;

     constructor(http: Http) {
       this.http = http;
     }
    */
    constructor(public http: Http){
    }

    makeRequest(): void {
      this.loading = true;
      // get请求
      this.http.request('http://xxxxx')
       .subscribe((res: Response) {
         this.data = res.json();
         this.loading = false;
       });
    }
}