Angular 学习笔记 (九) - HTTP Client
大多数前端应用都要通过 HTTP 协议与服务器通讯,才能下载或上传数据并访问其它后端服务。Angular 给应用提供了一个简化的 HTTP 客户端 API,也就是 @angular/common/http
中的 HttpClient
服务类。
一. 准备工作
1.1 项目中导入Http
app.module.ts
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { HttpClientModule } from '@angular/common/http'; @NgModule({ imports: [ BrowserModule, HttpClientModule, ], declarations: [ AppComponent, ], bootstrap: [ AppComponent ] }) export class AppModule {}
HttpClient
服务为所有工作都使用了Observable。你必须导入范例代码片段中出现的 RxJS 可观察对象和操作符。比如 ConfigService
中的这些导入就很典型。
1.2 模拟后端
模拟后端有多种方式,这里介绍一种
谷歌的Firebase
谷歌搜索 Firebase -> 新建一个项目 -> 选择新建一个Realtime Database。
之后就可以模拟向该Server发送Http数据.
二. 发送和接收数据
本例中的数据结构:
export class Post{ title: '' , content: '' } |
Post:
createAndStorePost(title: string, content: string) { const postData: Post = { title: title, content: content }; this.http .post<{ name: string }>( "https://project.firebaseio.com/posts.json", postData, { observe: "response", } ) .subscribe( (responseData) => { console.log(responseData); }, (error) => { this.error.next(error.message); } ); }
Fetch:
fetchPosts() { return this.http .get<{ [key: string]: Post }>( "https://project.firebaseio.com/posts.json", { headers: new HttpHeaders({ "Custom-Header": "hello" }), params: new HttpParams().set("print", "pretty"), responseType: 'json' } ) .pipe( map((responseData) => { const postsArray: Post[] = []; for (const key in responseData) { if (responseData.hasOwnProperty(key)) { postsArray.push({ ...responseData[key], id: key }); } } return postsArray; }), catchError((errorRes) => { // Send to analytics server return throwError(errorRes); }) ); }
三. 拦截器Interceptor
借助拦截机制,你可以声明一些拦截器,它们可以检查并转换从应用中发给服务器的 HTTP 请求。这些拦截器还可以在返回应用的途中检查和转换来自服务器的响应。多个拦截器构成了请求/响应处理器的双向链表。
拦截器可以用一种常规的、标准的方式对每一次 HTTP 的请求/响应任务执行从认证到记日志等很多种隐式任务。
如果没有拦截机制,那么开发人员将不得不对每次 HttpClient
调用显式实现这些任务。
实现一个拦截器:
1 import { HttpEventType, HttpHandler, HttpInterceptor, HttpRequest } from "@angular/common/http"; 2 import { map, tap } from "rxjs/operators"; 3 4 export class AuthInterceptorService implements HttpInterceptor { 5 6 intercept(req: HttpRequest<any>, next: HttpHandler) { 7 console.log('Request is on its way'); 8 console.log(req.url); 9 const modifiedRequest = req.clone({ 10 headers: req.headers.append('Auth', 'xyz') 11 }); 12 return next.handle(modifiedRequest).pipe(tap(event => { 13 console.log(event); 14 if (event.type === HttpEventType.Response) { 15 console.log('Response arrived, body data: '); 16 console.log(event.body); 17 } 18 })); 19 } 20 }
在app.module.ts:
providers: [{provide: HTTP_INTERCEPTORS, useClass: AuthInterceptorService, multi:true}],
分类:
前端
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具