您好,欢迎访问一九零五行业门户网

angular学习之浅析HttpClientModule模块

本篇文章带大家了解一下angular中的httpclientmodule模块,介绍一下请求方法、请求参数、响应内容、拦截器、angular proxy等相关知识,希望对大家有所帮助!
该模块用于发送 http 请求,用于发送请求的方法都返回 observable 对象。【相关教程推荐:《angular教程》】
1、快速开始1)、引入 httpclientmodule 模块
// app.module.tsimport { httpclientmodule } from '@angular/common/http';imports: [ httpclientmodule]
2)、注入 httpclient 服务实例对象,用于发送请求
// app.component.tsimport { httpclient } from '@angular/common/http';export class appcomponent { constructor(private http: httpclient) {}}
3)、发送请求
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<post[]>('/getallposts') .subscribe(response => console.log(response))
3、请求参数1、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;}
2、httpparamsoptions 接口
declare interface httpparamsoptions { fromstring?: string; fromobject?: { [param: string]: string | readonlyarray<string>; }; encoder?: httpparametercodec;}
3、使用示例
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 <name>
6.1 请求拦截
@injectable()export class authinterceptor implements httpinterceptor { constructor() {} // 拦截方法 intercept( // unknown 指定请求体 (body) 的类型 request: httprequest<unknown>, next: httphandler // unknown 指定响应内容 (body) 的类型 ): observable<httpevent<unknown>> { // 克隆并修改请求头 const req = request.clone({ setheaders: { authorization: "bearer xxxxxxx" } }) // 通过回调函数将修改后的请求头回传给应用 return next.handle(req) }}
6.2 响应拦截
@injectable()export class authinterceptor implements httpinterceptor { constructor() {} // 拦截方法 intercept( request: httprequest<unknown>, next: httphandler ): observable<any> { 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 proxy1、在项目的根目录下创建 proxy.conf.json 文件并加入如下代码
{ "/api/*": { "target": "http://localhost:3070", "secure": false, "changeorigin": true }}
/api/*:在应用中发出的以 /api 开头的请求走此代理
target:服务器端 url
secure:如果服务器端 url 的协议是 https,此项需要为 true
changeorigin:如果服务器端不是 localhost, 此项需要为 true
2、指定 proxy 配置文件 (方式一)
"scripts": { "start": "ng serve --proxy-config proxy.conf.json",}
3、指定 proxy 配置文件 (方式二)
"serve": { "options": { "proxyconfig": "proxy.conf.json" },
该模块用于发送 http 请求,用于发送请求的方法都返回 observable 对象。
更多编程相关知识,请访问:编程视频!!
以上就是angular学习之浅析httpclientmodule模块的详细内容。
其它类似信息

推荐信息