Angular中如何使用HttpClientModule模块
发表于:2025-02-08 作者:千家信息网编辑
千家信息网最后更新 2025年02月08日,这篇文章主要介绍Angular中如何使用HttpClientModule模块,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!该模块用于发送 Http 请求,用于发送请求的方法都返
千家信息网最后更新 2025年02月08日Angular中如何使用HttpClientModule模块
这篇文章主要介绍Angular中如何使用HttpClientModule模块,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
该模块用于发送 Http
请求,用于发送请求的方法都返回 Observable
对象。
1. 快速开始
引入 HttpClientModule
模块
// app.module.tsimport { httpClientModule } from '@angular/common/http';imports: [ httpClientModule]
注入 HttpClient
服务实例对象,用于发送请求
// app.component.tsimport { HttpClient } from '@angular/common/http';export class AppComponent { constructor(private http: HttpClient) {}}
发送请求
import { HttpClient } from "@angular/common/http"export class AppComponent implements OnInit { constructor(private http: HttpClient) {} ngOnInit() { this.getUsers().subscribe(console.log) } getUsers() { return this.http.get("https://jsonplaceholder.typicode.com/users") }}
2. 请求方法
this.http.get(url [, options]);this.http.post(url, data [, options]);this.http.delete(url [, options]);this.http.put(url, data [, options]);
this.http.get('/getAllPosts') .subscribe(response => console.log(response))
3. 请求参数
HttpParams
类
export declare class HttpParams { constructor(options?: HttpParamsOptions); has(param: string): boolean; get(param: string): string | null; getAll(param: string): string[] | null; keys(): string[]; append(param: string, value: string): HttpParams; set(param: string, value: string): HttpParams; delete(param: string, value?: string): HttpParams; toString(): string;}
HttpParamsOptions
接口
declare interface HttpParamsOptions { fromString?: string; fromObject?: { [param: string]: string | ReadonlyArray; }; encoder?: HttpParameterCodec;}
使用示例
import { HttpParams } from '@angular/common/http';let params = new HttpParams({ fromObject: {name: "zhangsan", age: "20"}})params = params.append("sex", "male")let params = new HttpParams({ fromString: "name=zhangsan&age=20"})
4. 请求头
请求头字段的创建需要使用 HttpHeaders
类,在类实例对象下面有各种操作请求头的方法。
export declare class HttpHeaders { constructor(headers?: string | { [name: string]: string | string[]; }); has(name: string): boolean; get(name: string): string | null; keys(): string[]; getAll(name: string): string[] | null; append(name: string, value: string | string[]): HttpHeaders; set(name: string, value: string | string[]): HttpHeaders; delete(name: string, value?: string | string[]): HttpHeaders;}
let headers = new HttpHeaders({ test: "Hello" })
5. 响应内容
declare type HttpObserve = 'body' | 'response';// response 读取完整响应体// body 读取服务器端返回的数据
this.http.get( "https://jsonplaceholder.typicode.com/users", { observe: "body" }).subscribe(console.log)
6. 拦截器
拦截器是 Angular
应用中全局捕获和修改 HTTP
请求和响应的方式。(Token
、Error
)
拦截器将只拦截使用 HttpClientModule
模块发出的请求。
$ ng g interceptor
6.1 请求拦截
@Injectable()export class AuthInterceptor implements HttpInterceptor { constructor() {} // 拦截方法 intercept( // unknown 指定请求体 (body) 的类型 request: HttpRequest, next: HttpHandler // unknown 指定响应内容 (body) 的类型 ): Observable > { // 克隆并修改请求头 const req = request.clone({ setHeaders: { Authorization: "Bearer xxxxxxx" } }) // 通过回调函数将修改后的请求头回传给应用 return next.handle(req) }}
6.2 响应拦截
@Injectable()export class AuthInterceptor implements HttpInterceptor { constructor() {} // 拦截方法 intercept( request: HttpRequest, next: HttpHandler ): Observable { return next.handle(request).pipe( retry(2), catchError((error: HttpErrorResponse) => throwError(error)) ) }}
6.3 拦截器注入
import { AuthInterceptor } from "./auth.interceptor"import { HTTP_INTERCEPTORS } from "@angular/common/http"@NgModule({ providers: [ { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true } ]})
7. Angular Proxy
在项目的根目录下创建 proxy.conf.json
文件并加入如下代码
{ "/api/*": { "target": "http://localhost:3070", "secure": false, "changeOrigin": true }}
/api/:在应用中发出的以
/api
开头的请求走此代理target:服务器端
URL
secure:如果服务器端
URL
的协议是https
,此项需要为true
changeOrigin:如果服务器端不是
localhost
, 此项需要为true
指定 proxy
配置文件 (方式一)
// package.json"scripts": { "start": "ng serve --proxy-config proxy.conf.json",}
指定 proxy
配置文件 (方式二)
// angular.json 文件中"serve": { "options": { "proxyConfig": "proxy.conf.json" },
以上是"Angular中如何使用HttpClientModule模块"这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注行业资讯频道!
模块
方法
服务
内容
文件
服务器
拦截器
对象
方式
应用
实例
篇文章
类型
配置
代码
价值
全局
兴趣
函数
参数
数据库的安全要保护哪些东西
数据库安全各自的含义是什么
生产安全数据库录入
数据库的安全性及管理
数据库安全策略包含哪些
海淀数据库安全审计系统
建立农村房屋安全信息数据库
易用的数据库客户端支持安全管理
连接数据库失败ssl安全错误
数据库的锁怎样保障安全
计算机网络安全建设
软件开发的收获和认识
服务器防火墙设置步骤
数据库怎么设置数据自增
常用文摘数据库
海思平台应用软件开发
发票税控开票软件服务器地址
国内网络安全事故盘点
网络技术最高工资
互联网教育科技创新大赛
考研网络安全专业好就业吗
通信网络技术员工作累吗
把文件上传到服务器
应用无线网络技术是什么
网络安全法对网络的安全性
梦付互联网科技公司上市了吗
新荣区现代化网络安全服务保障
饥荒联机 自建服务器
微信问卷调查 数据库
重生之互联网科技新贵
为什么qq服务器拒绝离线文件
公安部网络安全专家名单
河北一站式网络技术收费
看店宝怎么看数据库
网络安全宣传卡
宜兴运营计算机网络技术服务行业
税务优化管理服务器
300英雄登录服务器
数据库运维能做什么
网络安全法对网络的安全性