HttpClientModule控制模块使用方法

lxf2023-03-12 16:32:01

本文带大家了解一下Angular里的HttpClientModule控制模块,介绍一下HttpClientModule控制模块使用方法,希望能帮助到大家!

HttpClientModule控制模块使用方法

该控制模块用以推送 Http 要求,用以发送数据的方法都回到 Observable 目标。【有关实例教程强烈推荐:《angular教程》】

1. 快速开始

引进 HttpClientModule 控制模块

// app.module.ts
import { httpClientModule } from '@angular/common/http';
imports: [
  httpClientModule
]

引入 HttpClient 服务项目实例对象,用以发送数据

// app.component.ts
import { 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<Post[]>('/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<string>;
    };
    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 请求和响应的形式。(TokenError

回调函数将只阻拦应用 HttpClientModule 控制模块发出来的要求。

$ ng g interceptor <name>

HttpClientModule控制模块使用方法

HttpClientModule控制模块使用方法

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 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控制模块有什么作用?如何使用?的具体内容,大量欢迎关注AdminJS其他类似文章!