ホームページ  >  記事  >  ウェブフロントエンド  >  角度学習における HttpClientModule モジュールの簡単な分析

角度学習における HttpClientModule モジュールの簡単な分析

青灯夜游
青灯夜游転載
2022-05-24 12:09:171648ブラウズ

この記事では、angular の HttpClientModule モジュールを理解し、リクエスト メソッド、リクエスト パラメータ、応答コンテンツ、インターセプタ、Angular プロキシ、およびその他の関連知識を紹介します。みんな!

角度学習における HttpClientModule モジュールの簡単な分析

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

1. クイック スタート

1)、HttpClientModule モジュールを導入します

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

2)、リクエストの送信に使用される HttpClient サービス インスタンス オブジェクトの挿入

// app.component.ts
import { HttpClient } from '@angular/common/http';

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

3)、リクエストの送信

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.リクエストパラメータ

1.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;
}

2.HttpParamsOptionsインターフェイス

declare interface HttpParamsOptions {
    fromString?: string;
    fromObject?: {
        [param: string]: string | ReadonlyArray<string>;
    };
    encoder?: HttpParameterCodec;
}

3.使用例

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. インターセプター

インターセプターは、Angular アプリケーション HTTP におけるグローバル キャプチャおよび変更です。リクエストメソッドとレスポンスメソッド。 (トークン、エラー)

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

ng g インターセプタ <name></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

1. プロジェクトのルート ディレクトリに proxy.conf.json ファイルを作成し、次のコードを追加します

{
 	"/api/*": {
    "target": "http://localhost:3070",
    "secure": false,
    "changeOrigin": true
  }
}
  • /api/*: アプリケーションで発行された /api で始まるリクエストはこのプロキシを経由します

  • ターゲット: サーバーサイド URL

  • secure: サーバー側 URL のプロトコルが https の場合、この項目は true である必要があります

  • changeOrigin: サーバー側が localhost でない場合、この項目は true である必要がありますtrue

2. プロキシ構成ファイルを指定します (方法 1)

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

3. プロキシ構成ファイルを指定します (方法 2)

"serve": {
  "options": {
    "proxyConfig": "proxy.conf.json"
  },

このモジュールは Http リクエストの送信に使用され、リクエストの送信に使用されるメソッドはすべて Observable オブジェクトを返します。 。

プログラミング関連の知識について詳しくは、プログラミング ビデオをご覧ください。 !

以上が角度学習における HttpClientModule モジュールの簡単な分析の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

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