浅析Angular中HttpClientModule模块有什么用?怎么用?

 4238

本篇文章带大家了解一下Angular中的HttpClientModule模块,介绍一下HttpClientModule模块的使用方法,希望对大家有所帮助!


浅析Angular中HttpClientModule模块有什么用?怎么用?


该模块用于发送 Http 请求,用于发送请求的方法都返回 Observable 对象。


1. 快速开始

引入 HttpClientModule 模块

  1. // app.module.ts
  2. import { httpClientModule } from '@angular/common/http';
  3. imprts: [
  4.   httpClientModule
  5. ]

注入 HttpClient 服务实例对象,用于发送请求

  1. // app.component.ts
  2. import { HttpClient } from '@angular/common/http';
  3.  
  4. export class AppComponent {
  5.   constructor(private http: HttpClient) {}
  6. }

发送请求

  1. import { HttpClient } from "@angular/common/http"
  2.  
  3. export class AppComponent implements OnInit {
  4.   constructor(private http: HttpClient) {}
  5.   ngOnInit() {
  6.     this.getUsers().subscribe(console.log)
  7.   }
  8.   getUsers() {
  9.     return this.http.get("https://jsonplaceholder.typicode.com/users")
  10.   }
  11. }


2. 请求方法

  1. this.http.get(url [, options]);
  2. this.http.post(url, data [, options]);
  3. this.http.delete(url [, options]);
  4. this.http.put(url, data [, options]);
  1. this.http.get<Post[]>('/getAllPosts')
  2.   .subscribe(response => console.log(response))


3. 请求参数

HttpParams 类

  1. export declare class HttpParams {
  2.     constructor(options?: HttpParamsOptions);
  3.     has(param: string): boolean;
  4.     get(param: string): string | null;
  5.     getAll(param: string): string[] | null;
  6.     keys(): string[];
  7.     append(param: string, value: string): HttpParams;
  8.     set(param: string, value: string): HttpParams;
  9.     delete(param: string, value?: string): HttpParams;
  10.     toString(): string;
  11. }

HttpParamsOptions 接口

  1. declare interface HttpParamsOptions {
  2.     fromString?: string;
  3.     fromObject?: {
  4.         [param: string]: string | ReadonlyArray<string>;
  5.     };
  6.     encoder?: HttpParameterCodec;
  7. }

使用示例

  1. import { HttpParams } from '@angular/common/http';
  2.  
  3. let params = new HttpParams({ fromObject: {name: "zhangsan", age: "20"}})
  4. params = params.append("sex", "male")
  5. let params = new HttpParams({ fromString: "name=zhangsan&age=20"})


4. 请求头

请求头字段的创建需要使用 HttpHeaders 类,在类实例对象下面有各种操作请求头的方法。

  1. export declare class HttpHeaders {
  2.     constructor(headers?: string | {
  3.         [name: string]: string | string[];
  4.     });
  5.     has(name: string): boolean;
  6.     get(name: string): string | null;
  7.     keys(): string[];
  8.     getAll(name: string): string[] | null;
  9.     append(name: string, value: string | string[]): HttpHeaders;
  10.     set(name: string, value: string | string[]): HttpHeaders;
  11.     delete(name: string, value?: string | string[]): HttpHeaders;
  12. }
  1. let headers = new HttpHeaders({ test: "Hello" })


5. 响应内容

  1. declare type HttpObserve = 'body' | 'response';
  2. // response 读取完整响应体
  3. // body 读取服务器端返回的数据
  1. this.http.get(
  2.   "https://jsonplaceholder.typicode.com/users", 
  3.   { observe: "body" }
  4. ).subscribe(console.log)

6. 拦截器

拦截器是 Angular 应用中全局捕获和修改 HTTP 请求和响应的方式。(TokenError

拦截器将只拦截使用 HttpClientModule 模块发出的请求。

  1. $ ng g interceptor <name>

浅析Angular中HttpClientModule模块有什么用?怎么用?

6.1 请求拦截

  1. @Injectable()
  2. export class AuthInterceptor implements HttpInterceptor {
  3.   constructor() {}
  4.   // 拦截方法
  5.   intercept(
  6.     // unknown 指定请求体 (body) 的类型
  7.     request: HttpRequest<unknown>,
  8.     next: HttpHandler
  9.      // unknown 指定响应内容 (body) 的类型
  10.   ): Observable<HttpEvent<unknown>> {
  11.     // 克隆并修改请求头
  12.     const req = request.clone({
  13.       setHeaders: {
  14.         Authorization: "Bearer xxxxxxx"
  15.       }
  16.     })
  17.     // 通过回调函数将修改后的请求头回传给应用
  18.     return next.handle(req)
  19.   }
  20. }

6.2 响应拦截

  1. @Injectable()
  2. export class AuthInterceptor implements HttpInterceptor {
  3.   constructor() {}
  4.   // 拦截方法
  5.   intercept(
  6.     request: HttpRequest<unknown>,
  7.     next: HttpHandler
  8.   ): Observable<any> {
  9.     return next.handle(request).pipe(
  10.       retry(2),
  11.       catchError((error: HttpErrorResponse) => throwError(error))
  12.     )
  13.   }
  14. }

6.3 拦截器注入

  1. import { AuthInterceptor } from "./auth.interceptor"
  2. import { HTTP_INTERCEPTORS } from "@angular/common/http"
  3.  
  4. @NgModule({
  5.   providers: [
  6.     {
  7.       provide: HTTP_INTERCEPTORS,
  8.       useClass: AuthInterceptor,
  9.       multi: true
  10.     }
  11.   ]
  12. })


7. Angular Proxy

在项目的根目录下创建 proxy.conf.json 文件并加入如下代码

  1. {
  2.      "/api/*": {
  3.         "target": "http://localhost:3070",
  4.         "secure": false,
  5.         "changeOrigin": true
  6.       }
  7. }

/api/:在应用中发出的以 /api 开头的请求走此代理

target:服务器端 URL

secure:如果服务器端 URL 的协议是 https,此项需要为 true

changeOrigin:如果服务器端不是 localhost, 此项需要为 true

指定 proxy 配置文件 (方式一)

  1. // package.json
  2. "scripts": {
  3.   "start": "ng serve --proxy-config proxy.conf.json",
  4. }

指定 proxy 配置文件 (方式二)

  1. // angular.json 文件中
  2. "serve": {
  3.   "options": {
  4.     "proxyConfig": "proxy.conf.json"
  5. },


本文网址:https://www.zztuku.com/detail-9437.html
站长图库 - 浅析Angular中HttpClientModule模块有什么用?怎么用?
申明:如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐