angular - HttpClient

入门

引入 HttpClientModule 模块

//app.module.ts
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    HttpClientModule
  ],
})

注入服务实例

import { HttpClient } from '@angular/common/http';

export class AppComponent {
  constructor(private httpClient: HttpClient){}
}

httpClient 的方法

简单的案例

this.httpClient.get('https://jsonplaceholder.typicode.com/todos/1').subscribe(console.log);

返回结果

{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
}

get 请求里的 option 有什么

我们来看看 get 请求里的 option 里面的内容

options: {
        headers?: HttpHeaders | {   //头部字段将添加到 HTTP 请求中
            [header: string]: string | string[];
        };
        observe: 'response'; //返回一个 HttpResponse 对象,而不是一个 Observable
        context?: HttpContext;   //HttpContext 对象,用于传递与 HTTP 请求相关的上下文信息
        params?: HttpParams | {  //HttpParams 对象或一个包含键值对的对象,添加到 HTTP 请求的 URL 中
            [param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>;
        };
        reportProgress?: boolean;  //一个布尔值,如果为 true,则在请求过程中发送进度信息
        responseType?: 'json';   //其值应该是 "json"。这表明函数期望的响应类型是 JSON
        withCredentials?: boolean;  //一个布尔值,如果为 true,则允许跨站点访问控制(Cross-Site Access Control,CORS)请求携带凭据(如 cookies)
    }

HttpParams:配置 HTTP URL 参数

HttpParams

export declare class HttpParams {  
    // 私有属性:map 存储参数值  
    private map;  
    // 私有属性:encoder 用于编码和解码参数值  
    private encoder;  
    // 私有属性:updates 存储更新操作  
    private updates;  
    // 私有属性:cloneFrom 用于复制参数  
    private cloneFrom;  
    // 构造函数,接受可选的 HttpParamsOptions 参数  
    constructor(options?: HttpParamsOptions);  
  
    /**  
     * 判断请求体中是否包含给定参数的至少一个值  
     * @param param 参数名  
     * @returns 如果包含该参数的至少一个值,则返回 true,否则返回 false  
     */  
    has(param: string): boolean;  
  
    /**  
     * 获取给定参数的第一个值  
     * @param param 参数名  
     * @returns 如果存在该参数的第一个值,则返回该值,否则返回 null  
     */  
    get(param: string): string | null;  
  
    /**  
     * 获取给定参数的所有值  
     * @param param 参数名  
     * @returns 如果存在该参数的所有值,则返回一个字符串数组,否则返回 null  
     */  
    getAll(param: string): string[] | null;  
  
    /**  
     * 获取请求体中的所有参数名  
     * @returns 一个字符串数组,包含请求体中的所有参数名  
     */  
    keys(): string[];  
  
    /**  
     * 在现有参数值末尾添加一个新的值  
     * @param param 参数名  
     * @param value 要添加的新值  
     * @returns 一个包含新添加值的新 HttpParams 实例  
     */  
    append(param: string, value: string | number | boolean): HttpParams;  
  
    /**  
     * 根据给定的参数名和对应的值数组构造一个新的 HttpParams 实例  
     * @param params 包含参数名和对应值的对象,值为字符串、数字、布尔值或只读数组(包含字符串、数字、布尔值)  
     * @returns 一个包含新添加值的 HttpParams 实例  
     */  
    appendAll(params: {  
        [param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>;  
    }): HttpParams;  
  
    /**  
     * 替换给定参数的值  
     * @param param 参数名  
     * @param value 要替换的新值  
     * @returns 一个包含新替换值的新 HttpParams 实例  
     */  
    set(param: string, value: string | number | boolean): HttpParams;  
  
    /**  
     * 从请求体中移除给定的值或所有值(如果给定了多个值)  
     * @param param 要移除的参数名  
     * @param value 要移除的值(如果未提供该参数,则移除该参数的所有值)  
     * @returns 一个新的 HttpParams 实例,包含移除操作后的请求体内容  
     */  
    delete(param: string, value?: string | number | boolean): HttpParams;  
    /**
     *将主体序列化为经过编码的字符串,其中键值对(用=分隔)用&分隔。
     * @returns 返回经过编码的字符串
     */
    toString(): string;
    private clone;
    private init;
}

它实现的 HttpParamsOptions 接口

export declare interface HttpParamsOptions {
    /**
     * String representation of the HTTP parameters in URL-query-string format.
     * Mutually exclusive with `fromObject`.
     */
    fromString?: string;
    /** Object map of the HTTP parameters. Mutually exclusive with `fromString`. */
    fromObject?: {
        [param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>;
    };
    /** Encoding codec used to parse and serialize the parameters. */
    encoder?: HttpParameterCodec;
}

get 添加HttpParams参数实例:

因为get请求参数是param, 因为get请求 get(param: string): string | n

    //实例1
    let term = 'zhangsan'
    const options = term ? { params: new HttpParams({ fromObject: { 'age': 2 } }).set('name', term) } : {};

    this.httpClient.get('https://jsonplaceholder.typicode.com/todos/1', options).subscribe(console.log);

    //输出:https://jsonplaceholder.typicode.com/todos/1?age=2&name=zhangsan


    //实例2
    let httpParam2 = { params: new HttpParams({ fromObject: { 'name': 'lisi', 'age': 3 } }) };
    this.httpClient.get('https://jsonplaceholder.typicode.com/todos/1', httpParam2 ).subscribe(console.log);

    //输出:https://jsonplaceholder.typicode.com/todos/1?name=lisi&age=3

    //实例3
    let httpParam3 = new HttpParams({ fromObject: { 'name': 'lisi', 'age': 3 } });
    httpParam3 = httpParam3.append('aa', 'bb');
    this.httpClient.get('https://jsonplaceholder.typicode.com/todos/1', { params: httpParam3 }).subscribe(console.log);

    //输出:https://jsonplaceholder.typicode.com/todos/1?name=lisi&age=3&aa=bb

HTTP Header

export declare class HttpHeaders {
  /*
   *内部映射,将小写的头部名称映射到值。
  */
  private headers;
  /*
  *内部映射,将小写的头部名称映射到名称的规范化形式(首先看到的)。
  */
  private normalizedNames;
  /*
  *完成此对象的懒惰初始化(在读取之前需要)。
  */
  private lazyInit;
  /*
  下一个初始化时要排队执行的更新。
  */
  private lazyUpdate;
  /* 使用给定值构造一个新的HTTP标头对象。*/
  constructor(headers?: string | {
  [name: string]: string | number | (string | number)[];
  });
  /*
  检查是否存在给定的头部。
  @param name 要检查其存在性的头部名称。
  @returns 如果头部存在,则为true,否则为false。
  */
  has(name: string): boolean;
  /*
  检索给定头部的第一个值。
  @param name 头部名称。
  @returns 如果头部存在,则为值字符串,否则为null
  */
  get(name: string): string | null;
  /*
  检索头部的名称列表。
  @returns 头部名称的列表。
  */
  keys(): string[];
  /*
  检索给定头部的值列表。
  @param name 从其中检索值的头部名称。
  @returns 如果头部存在,则为值字符串的字符串,否则为null。
  */
  getAll(name: string): string[] | null;
  /*
  将新值附加到现有值集的末尾,并以原始实例的克隆形式返回它们。
  @param name 要附加值的头部名称。
  @param value 要附加的值。
  @returns 具有附加到给定头部的值的HTTP标头对象的克隆。
  */
  append(name: string, value: string | string[]): HttpHeaders;
  /*
  在原始实例的克隆中设置或修改给定头部的值。如果头部已经存在,它的值将用给定值替换返回对象中的值。
  @param name 头部名称。
  @param value 要设置或覆盖给定头部的值或值。
  @returns 具有新设置的标头值的HTTP标头对象的克隆。
  */
  set(name: string, value: string | string[]): HttpHeaders;
  /*
  在原始实例的克隆中删除给定头部的值。
  @param name 头部名称。
  @param value 要删除给定头部的值或值。
  @returns 具有已删除给定值的HTTP标头对象的克隆。
  */
  delete(name: string, value?: string | string[]): HttpHeaders;
  private maybeSetNormalizedName;
  private init;
  private copyFrom;
  private clone;
  private applyUpdate;
}

实例:

   let httpHeaders = new HttpHeaders({ test: "1111" });
    this.httpClient.get('https://jsonplaceholder.typicode.com/todos/1', { headers: httpHeaders }).subscribe(console.log);

响应内容

OBSERVE 和 RESPONSE 的类型

options: {
  …
  observe?: 'body' | 'events' | 'response',
  …
  responseType?: 'arraybuffer'|'blob'|'json'|'text',
  …
}

读取完整的响应体

可以用 get() 方法的 observe 选项来告诉 HttpClient,你想要完整的响应对象:

默认是 body

getConfigResponse(): Observable<HttpResponse<Config>> {
  return this.http.get<Config>(
    this.configUrl, { observe: 'response' });
}

拦截器

命令:ng g interceptor <name>

默认创建

import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor
} from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class RootInterceptor implements HttpInterceptor {

  constructor() {}

  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    return next.handle(request);
  }
}

请求拦截

响应拦截

拦截器使用

//app.module.ts
@NgModule({
  providers: [{
    provide: HTTP_INTERCEPTORS,
    useClass: RootInterceptor,
    multi: true
  },
  {
    provide: HTTP_INTERCEPTORS,
    useClass: ResponseInterceptor,
    multi: true
  }],
})
posted @ 2023-09-01 23:24  【唐】三三  阅读(26)  评论(0编辑  收藏  举报