Angular 4.3为我们提供了一种更简单的方式来处理HttpClient库中的http请求。它以新名称提供,以避免导致当前Http库发生重大更改。 HttpClient还为我们提供了高级功能,例如侦听进度事件和拦截器来监视或修改请求或响应。
Angular 4.3为我们提供了一种更简单的方式来处理HttpClient库中的http请求。它以新名称提供,以避免导致当前Http库发生重大更改。 HttpClient还为我们提供了高级功能,例如侦听进度事件和拦截器来监视或修改请求或响应。
确保你使用的是Angular 4.3或更高版本来试用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'; @NgModule({ declarations: [AppComponent], imports: [ BrowserModule, HttpClientModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule {}
然后,您可以像使用通常一样使用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返回响应的主体。您可以通过将观察键设置为“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 requests
制作POST,PUT或PATCH请求就如同一样简单:
postData() { this.http.post(this.url, this.payload).subscribe(); }
请注意,我们仍然需要subscribe才能提出请求。没有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,并且包含错误名称,错误消息和服务器状态等。
传递标题或查询参数的选项也可以使用传入的对象中的标题或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。这使得向用户显示进度条变得非常容易。
原创文章,作者:webstack,如若转载,请注明出处:https://www.webstacks.cn/tutorial/782.html