angular - HttpClient

【唐】三三 / 2023-09-02 / 原文

入门

引入 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
}

配置 HTTP URL 参数

HttpParams

class HttpParams {
  constructor(options: HttpParamsOptions = {} as HttpParamsOptions)
  has(param: string): boolean
  get(param: string): string | null
  getAll(param: string): string[] | null
  keys(): string[]
  append(param: string, value: string | number | boolean): HttpParams
  appendAll(params: { [param: string]: string | number | boolean | readonly (string | number | boolean)[]; }): HttpParams
  set(param: string, value: string | number | boolean): HttpParams
  delete(param: string, value?: string | number | boolean): HttpParams
  toString(): string
}

它实现的 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