Angular 的 HttpClient 简介

本文介绍了Angular4.3中HttpClient的升级,包括新名称的引入,以及如何使用它进行基础HTTP请求、监听进度事件和拦截器的功能。同时提到了如何安装和在项目中应用HttpClient,以及其与旧HttpAPI的不同之处。
摘要由CSDN通过智能技术生成

前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站

Angular 4.3 带来了一个更简单的处理 http 请求的新方法,使用了 HttpClient 库。为了避免对当前 Http 库造成破坏性改变,它以新的名称提供。HttpClient 还为我们提供了高级功能,比如能够监听进度事件和拦截器来监视或修改请求或响应。

安装

首先,你需要在你的应用模块中从 @angular/common/http 导入 HttpClientModule:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

import { AppComponent } from './app.component';

然后你可以像平常一样使用 HttpClient:

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

@Injectable()
export class DataService {
  constructor(private http: HttpClient) {}

基本用法

进行基本的 GET、POST、PUT、PATCH 或 DELETE 请求与旧的 Http API 非常相似。一个主要的区别是默认情况下期望一个 JSON 响应,因此不再需要显式解析 JSON 响应。

这是一个示例 GET 请求:

// ...

constructor(private http: HttpClient) {}

getData() {
  this.http.get(this.url).subscribe(res => {
    this.posts = res;
  });
}

如果你期望响应是 JSON 之外的其他内容,你可以使用一个带有 responseType 键的对象来指定期望的响应类型:

getData() {
  this.http.get(this.url, { responseType: 'text' }).subscribe(res => {
    this.data = res;
  });
}

你还可以为响应的形状定义一个接口,并对其进行类型检查:

interface Post {
  title: string;
  body: string;
};

// ...

constructor(private http: HttpClient) {}

getData() {
  this.http.get<Post>(this.url).subscribe(res => {
    this.postTitle = res.title;
  });
}

默认情况下,HttpClient 返回响应的主体。你可以传入一个带有 observe 键设置为 ‘response’ 值的对象来获取完整的响应。这对于检查某些标头可能很有用:

getData() {
  this.http.get<Post>(this.url, { observe: 'response' }).subscribe(res => {
    this.powered = res.headers.get('X-Powered-By');
    this.postTitle = res.body.title;
  });
}

发送 POST、PUT 和 PATCH 请求

进行 POST、PUT 或 PATCH 请求同样很容易:

postData() {
  this.http.post(this.url, this.payload).subscribe();
}

请注意,我们仍然需要订阅以使请求发出。没有订阅调用,请求是冷的。显然,你可能希望处理任何返回的响应或错误:

postData() {
  this.http.post(this.url, this.payload).subscribe(
    res => {
      console.log(res);
    },
    (err: HttpErrorResponse) => {
      console.log(err.error);
      console.log(err.name);
      console.log(err.message);
      console.log(err.status);
    }
  );
}

请求错误的类型是 HttpErrorResponse,其中包含错误名称、错误消息和服务器状态等信息。


还可以通过在作为第三个参数传入的对象中添加 headers 或 params 键来传递标头或查询参数到 POST、PUT 或 PATCH 请求:

updatePost() {
  this.http
    .put(this.url, this.payload, {
      params: new HttpParams().set('id', '56784'),
      headers: new HttpHeaders().set('Authorization', 'some-token')
    })
    .subscribe(...);
}

请注意这里使用了 HttpParams 和 HttpHeaders 类。你还需要从 @angular/common/http 中导入这些。

进度事件

HttpClient 的一个很棒的新功能是能够监听进度事件。这可以在任何类型的请求上进行,请求事件的生命周期中会提供不同的信息。以下是一个使用 GET 请求的完整示例:

import { Injectable } from '@angular/core';
import {
  HttpClient,
  HttpRequest,
  HttpEvent,
  HttpEventType
} from '@angular/common/http';

@Injectable()
export class DataService {
  url = '/some/api';

  constructor(private http: HttpClient) {}

  getData() {
    const req = new HttpRequest('GET', this.url, {
      reportProgress: true
    });

    this.http.request(req).subscribe((event: HttpEvent<any>) => {
      switch (event.type) {
        case HttpEventType.Sent:
          console.log('Request sent!');
          break;
        case HttpEventType.ResponseHeader:
          console.log('Response header received!');
          break;
        case HttpEventType.DownloadProgress:
          const kbLoaded = Math.round(event.loaded / 1024);
          console.log(`Download in progress! ${ kbLoaded }Kb loaded`);
          break;
        case HttpEventType.Response:
          console.log('😺 Done!', event.body);
      }
    });
  }
}
  • 首先,我们需要通过创建 HttpRequest 类的实例并使用 reportProgress 选项来构建一个请求对象。
  • 然后,我们订阅我们的请求对象以发起请求,并在请求的生命周期中监听不同的事件类型。我们可以根据事件类型做出适当的反应。可用的事件类型有 Sent、UploadProgress、ResponseHeader、DownloadProgress、Response 和 User。
  • 在上面的示例中,我们从 GET 响应中获取到目前为止下载的数据量,对于像 POST 或 PUT 请求,我们也可以通过类似 100 * event.loaded / event.total 的方式获取上传的负载百分比。这使得向用户显示进度条变得非常容易。

本文介绍了 HttpClient 的基础知识,下一步将介绍拦截器的使用,这是 HttpClient 的杀手功能。你也可以查看官方文档以深入了解。

  • 17
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

白如意i

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值