ホームページ  >  記事  >  ウェブフロントエンド  >  Angular での HttpClientModule モジュールの用途について簡単に分析します。使い方?

Angular での HttpClientModule モジュールの用途について簡単に分析します。使い方?

青灯夜游
青灯夜游転載
2021-09-28 10:53:272185ブラウズ

この記事では、Angular の HttpClientModule モジュールについて説明し、HttpClientModule モジュールの使用方法を紹介します。

Angular での HttpClientModule モジュールの用途について簡単に分析します。使い方?

このモジュールは Http リクエストの送信に使用され、リクエストの送信に使用されるメソッドはすべて Observable オブジェクトを返します。 [関連チュートリアルの推奨事項: "angular チュートリアル"]

1. クイック スタート

はじめにHttpClientModule Module

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

InjectionHttpClient リクエストの送信に使用されるサービス インスタンス オブジェクト

// 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[]>(&#39;/getAllPosts&#39;)
  .subscribe(response => console.log(response))

3. リクエストパラメータ

##HttpParams Class

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 &#39;@angular/common/http&#39;;

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 = &#39;body&#39; | &#39;response&#39;;
// response 读取完整响应体
// body 读取服务器端返回的数据
this.http.get(
  "https://jsonplaceholder.typicode.com/users", 
  { observe: "body" }
).subscribe(console.log)

6. インターセプタ

Interceptors は、グローバル

Angular アプリケーションが HTTP リクエストとレスポンスをキャプチャおよび変更するための方法です。 (Token, Error)

インターセプターは、

HttpClientModule モジュールを使用して行われたリクエストのみをインターセプトします。

$ ng g interceptor <name>

Angular での HttpClientModule モジュールの用途について簡単に分析します。使い方?

Angular での 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
構成ファイルを指定する (方法 1)

// package.json
"scripts": {
  "start": "ng serve --proxy-config proxy.conf.json",
}
Specify proxy

構成ファイル (方法 2) )

// angular.json 文件中
"serve": {
  "options": {
    "proxyConfig": "proxy.conf.json"
  },
プログラミング関連の知識の詳細については、プログラミング入門

を参照してください。 !

以上がAngular での HttpClientModule モジュールの用途について簡単に分析します。使い方?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はjuejin.cnで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。